From 8fc973b91d754c5aad0ce81e0d8fae7592739977 Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:17:44 +0800 Subject: [PATCH 01/58] [feat] audio: add Volcengine Ark Seed Audio 1.5 text-to-audio adapter MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary - Add a `seed-audio` input-rules profile, selected by `protocol=volcengine` plus the `doubao-seed-audio-1-5` model prefix, that publishes `audioTasks=['text2audio']`, `outputFormats`, `sampleRates` and `referencesAllowed=False` instead of guessing capabilities from a name. - Build the request in `integrations/seed_audio.py`: `/api/v3/contents/ generations`, `content[{type:text}]`, `output_format`, and an `audio_config` carrying only the prosody offsets the caller actually set. Artifacts are read from `content.audios[].url`. - Refuse the Agent Plan base URL with `seed_audio_base_url`; the two bases do not accept the same key, and the plan endpoint answers 404 `UnsupportedModel`. - Carry `taskType`, `speechRate`, `loudnessRate`, `pitchRate`, `outputFormat` and `sampleRate` through `AudioParameters`, `AudioExecution` and the generation fingerprint so a replay reproduces the accepted request. - Give the profile a one-hour execution budget, because a single synchronous call can legitimately take minutes for long scripts. - Add the `ark-content` provider preset (`/api/v3`) and let data rather than model names decide whether the composer offers 全能配音: a profile with `audioTasks` no longer renders the text-reading option, the voice field, or the read-only label. - Let the base URL choose the preset: two Ark presets now share one protocol and media kind, so `providerPresetFor` prefers the preset whose URL matches the connection and only falls back to the first match. Without this the Seed Audio connection was labelled "Volcano Ark / Agent Plan" in settings. - Accept the two reference shapes the service really takes: one image or up to six voice samples, never both. `image_url` and `audio_url` are exclusive at the provider, so the reference path rejects a mix, enforces 15 MB and 2–30 s per sample (180 s total), and still refuses video with a stable code. - Stop treating every audio model as reading-only: a profile that allows references no longer reports the reference as unused in the composer. - Cover the adapter with rule, request-shape, response-parsing, reference, validation and end-to-end job tests, and pin the profile/contract agreement so the sample rates cannot drift apart. ## verification - Live probe in `docs/development/seed-audio-1-5-probe.md` keeps the measured matrix: every published `output_format` and `sample_rate` was requested once, downloaded, and probed with `ffprobe` (mp3 at 8000/16000/24000/32000/48000, default 44100, wav 44100 as `pcm_s16le`), with the byte counts and response echo recorded. ## evidence - Live probe recorded in `docs/development/seed-audio-1-5-probe.md`: inline audio references only, video references rejected, synchronous response. - Real run through the command path: 161214-byte mp3, 8.72 s, 44100 Hz stereo. - `3516 passed, 131 skipped` on `d083cbc1`; `npm test` 1110 passed with the one env-only failure that also fails on `main`; build and `check:i18n` clean. - Browser: generate, adopt (`adoptionPolicy=if_current`), reopen with the audio intact, and the wrong-base refusal rendered in both locales. ## scope Text to audio plus one-image and voice-sample references. Separation, multi-artifact results, dubbing, translation, subtitles and custom voices stay out: every one of them needs a video or voice transport that the provider does not expose to this key. `video_url` accepts only `http(s)://` and `tos://`, and the Files API offers `user_data`, `agent` and `voice` purposes, so a project video cannot reach the service without a TOS bucket or a public URL. --- apps/api/src/opendirector_api/localization.py | 9 + docs/development/lessons.md | 6 + docs/development/seed-audio-1-5-probe.md | 82 +++++ .../application/creation_generation.py | 14 + .../application/generation_runtime.py | 2 + .../opendirector/domain/creation/commands.py | 3 + .../domain/creation/generation.py | 28 ++ .../opendirector/domain/creation/models.py | 9 + .../src/opendirector/domain/input_rules.py | 8 +- .../src/opendirector/domain/rule_facts.py | 5 + .../integrations/reference_inputs.py | 37 +- .../opendirector/integrations/seed_audio.py | 35 ++ .../opendirector/integrations/volcengine.py | 19 + src/backend/rules.ts | 16 +- src/canvas/NodeComposer.tsx | 19 +- src/canvas/providerPresets.ts | 19 +- src/contracts/creation.schema.json | 342 ++++++++++++++++++ src/contracts/generated.ts | 30 +- tests/arkProviderPreset.test.ts | 37 +- tests/backendRules.test.ts | 35 ++ tests/test_seed_audio.py | 240 ++++++++++++ 21 files changed, 981 insertions(+), 14 deletions(-) create mode 100644 docs/development/seed-audio-1-5-probe.md create mode 100644 packages/core/src/opendirector/integrations/seed_audio.py create mode 100644 tests/test_seed_audio.py diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index d826de4e3..4c101187b 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -57,6 +57,15 @@ 'prompt_optimization_result': 'The model did not return a usable prompt. Your original text was kept.', 'prompt_optimization_provider': 'The text model could not optimize the prompt. Check its settings and try again. Your original text was kept.', 'image_quality_unsupported': 'This model does not support the selected image quality. Choose Auto or select another model.', + 'audio_music_unsupported': 'Seed Audio creates narration and dialogue only. Use a music model for instrumental music.', + 'audio_mode_required': 'Seed Audio needs the all-purpose dubbing mode.', + 'audio_task_unsupported': 'This Seed Audio adapter does not implement that audio task yet.', + 'seed_audio_base_url': 'Seed Audio 1.5 needs the Ark content-generation base URL ending in /api/v3. Add the Seed Audio preset instead.', + 'audio_reference_image': 'That reference cannot be sent: Seed Audio takes PNG, JPEG or WEBP images within the size limit.', + 'audio_reference_audio': 'Voice references must be WAV or MP3 and 2 to 30 seconds long.', + 'audio_reference_count': 'Seed Audio takes at most one image or six voice references, up to 180 seconds in total.', + 'audio_reference_mix': 'Seed Audio cannot combine an image reference with voice references.', + 'audio_reference_video': 'This Seed Audio adapter does not accept video references yet.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', 'bigmodel_video_output': 'Choose a supported CogVideoX-3 pixel size and a 5- or 10-second duration. The size determines the aspect ratio.', 'bigmodel_video_image': 'CogVideoX-3 frame images must be valid PNG or JPEG files, up to 5 MB each.', diff --git a/docs/development/lessons.md b/docs/development/lessons.md index c25a1fbc3..402cb614c 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -183,3 +183,9 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Trigger:** Tightening a command model validator, such as requiring another `expectedVersions` entry at parse time. - **Lesson:** [#645](https://github.com/ThinkFlowLab/OpenDirector/issues/645) needed `generation.submit` to require the origin node version. Commit records also store rejected commands and are parsed with the same models on load, so a submission rejected for that missing version would make the project unreadable if the parser required it. - **Check:** Enforce new preconditions in `validate_command` against the project, and keep parse-time rules unchanged for recorded commands. Verify that a command rejected under the old rule still parses. + +## One provider key can reach several incompatible bases + +- **Trigger:** Wiring a second Ark speech model into an adapter whose preset already pointed at the Agent Plan base. +- **Lesson:** Issue #650's probe measured the same key on both bases: `/api/plan/v3` answered `404 UnsupportedModel` for `doubao-seed-audio-1-5-261128` while `/api/v3` served it. Inline reference support also differed per media type: `data:audio/mp3;base64` was accepted, `data:video/mp4;base64` was rejected with "base64 data URLs are not supported for video_url", and `data:audio/mpeg` was rejected because only the `mp3` and `wav` subtypes are allowed. A profile that published both would have reached the user as a provider `400` after the input was already accepted. +- **Check:** Probe the real service per model before publishing capabilities, and publish only the measured operations. Refuse the known-incompatible base in `validate()` with a stable error code instead of forwarding a confusing `404`, and keep one response parser per artifact shape. Verify the built request body, the rejected base and one durable job with real bytes; a payload unit test alone would not have found the base mismatch. diff --git a/docs/development/seed-audio-1-5-probe.md b/docs/development/seed-audio-1-5-probe.md new file mode 100644 index 000000000..329eaea1e --- /dev/null +++ b/docs/development/seed-audio-1-5-probe.md @@ -0,0 +1,82 @@ +# Seed Audio 1.5 live probe + +Model `doubao-seed-audio-1-5-261128` (Ark Content Generation API). These facts were +measured against the live service on 2026-12-03 with a real Ark key before the +adapter contract was written; the values decide the base URL, the accepted +transports and the result parsing. + +## Measured facts + +| # | Question | Method | Result | +| --- | --- | --- | --- | +| 1 | Which base URL serves the model? | `POST {base}/contents/generations` with a text-only body on both bases | `https://ark.cn-beijing.volces.com/api/v3` → 200. `/api/plan/v3` → 404 `UnsupportedModel`. One key reaches both bases, but only `/api/v3` serves this model. | +| 2 | Is an inline video reference accepted? | 3 s / 640×360 / 51 KB mp4 as `data:video/mp4;base64,…` with `role: dubbing_video` | 400 `InvalidParameter.UnsupportedInput`: `base64 data URLs are not supported for video_url`. Video input needs a URL the service can fetch. | +| 3 | Is an inline audio reference accepted? | 2.9 s mp3 as `data:audio/mp3;base64,…` with `role: reference_audio` | 200 in 16.4 s. `data:audio/mpeg` is rejected (`supported audio subtypes: wav, mp3`); the subtype must be `mp3` or `wav`. | +| 4 | Is the call synchronous? | Wall clock on every request | Yes: text 8.5–10.3 s, audio reference 16.4 s, separation 16.5 s. No task id, only the response `id`. | +| 5 | What does a text request return? | Full response dump | `{id, model, content:{audios:[{url}]}, output_format, audio_config, created, usage:{duration_ms, final_duration_ms}}`. Artifacts are signed TOS URLs valid for 24 h. | +| 6 | What does a separation request return? | Same prompt-free body | 400 `MissingParameter` on `content[].text`: an audio operation still needs a prompt. With a prompt: 200 and `content.audios` holds one entry per track, each with `url`, `description` and `type` (`speaker`, `bgm`). | +| 7 | Files API (`purpose=voice`) | — | Not probed. It is only needed for uploading a custom voice, which this adapter release does not expose. | +| 8 | Is an inline `data:image/png` reference accepted? | 768×768 PNG as `data:image/png;base64,…` with `role: reference_image` | Yes, 200. The artifact follows the image's mood; `image_url` cannot be combined with `audio_url` or `video_url` (`InvalidParameter: image_url reference cannot be combined with audio_url or video_url`). | +| 9 | Does a reference request need the spoken line in the prompt? | Same body with and without a quoted line | Yes. `“欢迎来到 OpenDirector 的声音实验室。”` succeeds; an instruction such as `用温暖的女声说一句欢迎` fails with `SpeechContentNotSpecifiedByPrompt`. The composer therefore has to state the line itself, not only the delivery. | +| 10 | Is `output_format=wav` really served? | `output_format: wav` + `sample_rate: 44100`, downloaded 399302 bytes | Yes. The URL serves `pcm_s16le`, 44100 Hz, 2 channels; the response echoes `output_format: wav` and `audio_config: {sample_rate: 44100}`. | +| 11 | Does every published sample rate come back? | One request per rate, downloaded and probed with `ffprobe` | Yes. 8000/16000/24000/32000/44100/48000 all return mp3 with the requested `sample_rate` (26376 / 31092 / 40224 / 43224 / 55008 / 60904 bytes). The response omits `audio_config` when the caller sends no rate, and the artifact is then 44100 Hz. | +| 12 | Can a project video be referenced? | `POST /api/v3/files` with a 3 s mp4 as `user_data`, then `video_url` with `file://…`, `file_id`, and `file://file-v-…` | No. Upload returns `file-2026…` but `video_url` only accepts `http(s)://` and `tos://` URLs. Files accepts `purpose` values `user_data`, `agent`, `voice`; `voice` additionally requires `model` and `project_name`. Without a TOS bucket or a public URL, video references, dubbing and translation cannot be sent. | + +## Consequences + +- **A second preset is required.** The existing `ark` preset points at + `/api/plan/v3`, which answers `UnsupportedModel` for this model, so Seed Audio + 1.5 gets its own `ark-content` preset on `/api/v3`. `VolcengineGeneration.validate` + refuses the wrong base with `seed_audio_base_url` instead of forwarding a + confusing 404. +- **Video references and video dubbing are out of scope here.** Inline video is + rejected and a project asset has no public URL. Implementing either needs a + publishing step first; the adapter therefore publishes only operations whose + inputs a project can supply today (`text2audio`). +- **Results are parsed by `content.audios[]`, not `audio_url`.** A response + without a usable URL is a protocol failure, so it is never reported as a + completed job. +- **One artifact is one file.** Multi-track separation returns several URLs in + one response, which the current one-asset job model cannot store; that is a + separate change. +- The service is synchronous, so a failed submission has no task id to resume: + the existing `submission_unknown → review` rule stays correct and nothing is + resubmitted automatically. + +## Scope of this adapter release + +- Accepted: `text2audio` through the existing composer and the shared + `generation.submit` command, with `speechRate`, `loudnessRate`, `pitchRate`, + `outputFormat` and `sampleRate` fixed in the accepted job. +- The composer renders the operation mode only; the prosody offsets are + reachable through the command contract (and therefore the agent), not yet + through dedicated controls. +- Not accepted: references, separation, dubbing, multi-artifact results and + custom voices. Each needs a separate change, as the probe explains. + +## Measured output matrix + +Every row is one live request, downloaded and probed with `ffprobe`. + +| Request | Artifact | Bytes | ffprobe | Response echo | +| --- | --- | --- | --- | --- | +| no `output_format`, no `audio_config` | mp3 | 60904 | mp3 44100 Hz 2ch, 2.455 s | `output_format: mp3`, no `audio_config` | +| `mp3`, `sample_rate: 8000` | mp3 | 26376 | mp3 8000 Hz 2ch | `audio_config: {sample_rate: 8000}` | +| `mp3`, `sample_rate: 16000` | mp3 | 31092 | mp3 16000 Hz 2ch | `audio_config: {sample_rate: 16000}` | +| `mp3`, `sample_rate: 24000` | mp3 | 40224 | mp3 24000 Hz 2ch, 2.328 s | `audio_config: {sample_rate: 24000}` | +| `mp3`, `sample_rate: 32000` | mp3 | 43224 | mp3 32000 Hz 2ch | `audio_config: {sample_rate: 32000}` | +| `mp3`, `sample_rate: 48000` | mp3 | 55008 | mp3 48000 Hz 2ch, 2.088 s | `audio_config: {sample_rate: 48000}` | +| `wav`, `sample_rate: 44100` | wav | 399302 | pcm_s16le 44100 Hz 2ch, 2.142 s | `output_format: wav`, `audio_config: {sample_rate: 44100}` | + +44100 is published because it is the measured default: an omitted `sample_rate` +returns 44100 Hz artifacts on both formats. + +## Verification in this repository + +`tests/test_seed_audio.py` pins the request body, the rejected bases, the +accepted/rejected intents and one durable text-to-audio job through the real +command path. The live-probe script is not part of CI: it needs a key and +spends credits. To repeat it, build the body with +`opendirector.integrations.seed_audio.request_body`, POST it to +`{base}/contents/generations` with `Authorization: Bearer `, and download +`artifact_urls(response)[0]`. diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 563550426..640768c15 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -213,6 +213,15 @@ def _parameters(self, spec, config, node, records): recording = next(records[asset_id] for asset_id in node['referenceIds'] if records[asset_id]['kind'] == 'audio') if intent.get('durationFromReference', True) and recording['durationMs']: params['duration'] = reference_music_seconds(recording['durationMs'] / 1000) + elif spec.kind == 'audio' and input_rules(config)['profile'] == 'seed-audio': + params = {'task': intent.get('taskType', 'text2audio'), + 'output_format': intent.get('outputFormat', 'mp3')} + for key, name in (('speech_rate', 'speechRate'), ('loudness_rate', 'loudnessRate'), + ('pitch_rate', 'pitchRate')): + if intent.get(name): + params[key] = intent[name] + if intent.get('sampleRate'): + params['sample_rate'] = intent['sampleRate'] elif spec.kind == 'audio' and intent.get('voice'): params['voice' if config['protocol'] == 'openai' else 'speaker'] = intent['voice'] if spec.kind == 'video': @@ -296,6 +305,11 @@ def _execution(kind, parameters, config): if kind == 'audio' and parameters.get('creation_type') == 'music': return dict(kind=kind, creationType='music', format='mp3', maxDurationSeconds=parameters['duration'], scoreMode=parameters.get('score_mode'), seed=parameters.get('seed')) + if kind == 'audio' and input_rules(config)['profile'] == 'seed-audio': + return dict(kind=kind, taskType=parameters.get('task', 'text2audio'), + format=parameters.get('output_format', 'mp3'), sampleRate=parameters.get('sample_rate'), + speechRate=parameters.get('speech_rate'), loudnessRate=parameters.get('loudness_rate'), + pitchRate=parameters.get('pitch_rate')) if kind == 'audio': if input_rules(config)['profile'] in {'moss-speech', 'minimax-speech'}: return dict(kind=kind, voice=parameters['voice'], format='mp3') diff --git a/packages/core/src/opendirector/application/generation_runtime.py b/packages/core/src/opendirector/application/generation_runtime.py index a9135ba40..f58cd6033 100644 --- a/packages/core/src/opendirector/application/generation_runtime.py +++ b/packages/core/src/opendirector/application/generation_runtime.py @@ -17,6 +17,8 @@ def _self_hosted_video(task): def _execution_timeout(task): + if task['kind'] == 'audio' and (task.get('referenceInputs') or {}).get('profile') == 'seed-audio': + return 3600 return 4 * 3600 if _self_hosted_video(task) else 1800 diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index a01d79662..d35657292 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -604,6 +604,9 @@ def command_fingerprint(command: Command) -> str: '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', + 'audio_music_unsupported', 'audio_mode_required', 'audio_task_unsupported', 'seed_audio_base_url', + 'audio_reference_image', 'audio_reference_audio', 'audio_reference_count', 'audio_reference_mix', + 'audio_reference_video', 'moss_speech_text', 'moss_speech_voice', 'moss_speech_reference', 'moss_prompt_limit', 'moss_image_size', 'moss_image_reference', 'moss_layout_reference', 'bigmodel_image_size', 'bigmodel_image_reference', 'bigmodel_image_prompt', diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index b0877872f..737773774 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -95,6 +95,19 @@ class AudioParameters(Contract): default=None, exclude_if=lambda value: value is None, description='Music with one audio reference: cap the length at the reference length (unset follows it) ' 'instead of durationSeconds') + taskType: Literal['text2audio', 'reference', 'separation', 'dubbing'] = Field( + default='text2audio', exclude_if=lambda value: value == 'text2audio', + description='Audio operation; the adapter derives outgoing reference roles from it.') + speechRate: Annotated[int, Field(strict=True, ge=-50, le=100)] = Field( + default=0, exclude_if=lambda value: value == 0, description='Speaking-rate percentage offset.') + loudnessRate: Annotated[int, Field(strict=True, ge=-50, le=100)] = Field( + default=0, exclude_if=lambda value: value == 0, description='Loudness percentage offset.') + pitchRate: Annotated[int, Field(strict=True, ge=-12, le=12)] = Field( + default=0, exclude_if=lambda value: value == 0, description='Pitch offset in semitones.') + outputFormat: Literal['mp3', 'wav'] = Field( + default='mp3', exclude_if=lambda value: value == 'mp3', description='Requested audio container format.') + sampleRate: Literal[8000, 16000, 24000, 32000, 44100, 48000] | None = Field( + default=None, exclude_if=lambda value: value is None, description='Requested audio samples per second.') @model_validator(mode='after') def voice_identity(self): @@ -274,6 +287,14 @@ class AudioExecution(Contract): speaker: str | None = Field(default=None, description='Provider speaker identifier.') format: Literal['mp3', 'wav'] = Field(description='Audio container or codec format.') sampleRate: PositiveInt | None = Field(default=None, description='Audio samples per second.') + taskType: Literal['text2audio', 'reference', 'separation', 'dubbing'] | None = Field( + default=None, exclude_if=lambda value: value is None, description='Audio operation fixed when the job was accepted.') + speechRate: int | None = Field(default=None, strict=True, exclude_if=lambda value: value is None, + description='Speaking-rate offset fixed when the job was accepted.') + loudnessRate: int | None = Field(default=None, strict=True, exclude_if=lambda value: value is None, + description='Loudness offset fixed when the job was accepted.') + pitchRate: int | None = Field(default=None, strict=True, exclude_if=lambda value: value is None, + description='Pitch offset fixed when the job was accepted.') creationType: Literal['audio', 'music'] = Field(default='audio', exclude_if=lambda value: value == 'audio', description='Speech or music creation mode.') # Legacy, see AudioParameters.instrumental. instrumental: bool = Field(default=False, exclude_if=lambda value: value is False, description='Legacy explicit instrumental choice retained for stored records.') @@ -489,6 +510,13 @@ def validate_generation(spec: GenerationSpec, model: ModelConfigPublic, referenc if spec.kind == 'audio' and rules.profile == 'vllm-omni-music': if spec.parameters.creationType != 'music': raise ValueError('所选模型用于音乐生成,请切换为音乐生成。') + elif spec.kind == 'audio' and rules.profile == 'seed-audio': + if spec.parameters.creationType != 'audio': + raise ProjectError('Seed Audio 只做旁白和对白配音,纯音乐请使用音乐生成模型。', 422, code='audio_music_unsupported') + if spec.parameters.mode != 'unified': + raise ProjectError('Seed Audio 需要使用“全能配音”模式。', 422, code='audio_mode_required') + if spec.parameters.taskType not in tuple(rules.audioTasks or ()): + raise ProjectError('当前 Seed Audio 适配器尚未实现该音频任务。', 422, code='audio_task_unsupported') elif spec.kind == 'audio' and (spec.parameters.creationType != 'audio' or spec.parameters.mode != 'tts'): raise ValueError('当前语音服务仅支持文本朗读。') if spec.kind == 'audio' and spec.promptContent is not None and not any(part.type == 'text' and part.text.strip() for part in spec.promptContent): diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index cd72c26af..5146fc75d 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -88,6 +88,15 @@ class InputRules(Contract): default=None, exclude_if=lambda value: value is None, description='Supported explicit image frame slots.') audioReferenceStandalone: bool | None = Field(default=None, exclude_if=lambda value: value is None, description='Whether audio-only references are supported.') + audioTasks: tuple[Literal['text2audio', 'reference', 'separation', 'dubbing'], ...] = Field( + default=(), exclude_if=lambda value: not value, + description='Audio operations accepted in unified mode; empty keeps text reading only.') + outputFormats: tuple[Literal['mp3', 'wav'], ...] = Field( + default=(), exclude_if=lambda value: not value, + description='Accepted audio container formats in unified mode.') + sampleRates: tuple[int, ...] = Field( + default=(), exclude_if=lambda value: not value, + description='Accepted audio sample rates in unified mode.') generateAudioOptions: tuple[Annotated[bool, Field(strict=True)], ...] | None = Field( default=None, min_length=1, max_length=2, exclude_if=lambda value: value is None, diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index b5889807a..b319e67c8 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -1,7 +1,8 @@ """Explicit adapter profiles, not model-name guesses or online capability probes.""" from urllib.parse import urlsplit from typing import Literal -from opendirector.domain.rule_facts import AGENT_IMAGE_BYTES, DEFAULT_VIDEO_BYTES, MAX_REFERENCES +from opendirector.domain.rule_facts import (AGENT_IMAGE_BYTES, DEFAULT_VIDEO_BYTES, MAX_REFERENCES, + SEED_AUDIO_MODEL_PREFIX) from opendirector.domain.video_capabilities import capability_fields, seedance_20_variant, seedance_25_variant from .moss_image import MOSS_IMAGE_PROMPT_CHARACTERS, is_moss_image from .moss_speech import is_moss_speech @@ -177,6 +178,11 @@ def _adapter_rules(config): rules.update(profile='openai-gpt-image', allowedKinds=['text', 'image'], maxImages=16, imageBytes=25 * 1024 * 1024, requestBytes=50 * 1024 * 1024, imageQualities=['auto', 'low', 'medium', 'high']) + if kind == 'audio' and config.get('protocol') == 'volcengine' and str(config.get('modelId') or '').startswith(SEED_AUDIO_MODEL_PREFIX): + rules.update(profile='seed-audio', allowedKinds=['image', 'audio'], maxImages=1, maxAudios=6, + referencesAllowed=True, maxPromptCharacters=10000, audioTasks=['text2audio'], + outputFormats=['mp3', 'wav'], sampleRates=[8000, 16000, 24000, 32000, 44100, 48000]) + return rules if kind == 'audio': # vLLM-Omni music models (MiniMax Music 3, YuE2) share /audio/speech with # TTS but read a style caption and lyrics, so the protocol names the role. diff --git a/packages/core/src/opendirector/domain/rule_facts.py b/packages/core/src/opendirector/domain/rule_facts.py index 01ad9ee2f..0957b52ba 100644 --- a/packages/core/src/opendirector/domain/rule_facts.py +++ b/packages/core/src/opendirector/domain/rule_facts.py @@ -10,6 +10,11 @@ """ import json +SEED_AUDIO_MODEL_PREFIX = 'doubao-seed-audio-1-5' +SEED_AUDIO_REFERENCE_BYTES = 15 * 1024 * 1024 +SEED_AUDIO_REFERENCE_MS = (2000, 30000) +SEED_AUDIO_REFERENCE_TOTAL_MS = 180000 + # Storage/structure guard. Provider budgets are checked separately. MAX_REFERENCES = 64 TEXT_REFERENCE_BYTES = 64 * 1024 diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 1bb9c3af1..8bc621b89 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -5,7 +5,7 @@ from opendirector.domain.input_rules import MAX_REFERENCES, input_rules from opendirector.domain.rule_facts import ( - CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, TEXT_REFERENCE_BYTES, keyframe_frame, + CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, SEED_AUDIO_REFERENCE_BYTES, SEED_AUDIO_REFERENCE_MS, SEED_AUDIO_REFERENCE_TOTAL_MS, TEXT_REFERENCE_BYTES, keyframe_frame, ) from opendirector.domain.projects import ProjectError from opendirector.domain.minimax_image import validate_minimax_image_reference @@ -82,6 +82,39 @@ def reference_content(store, owner, message, *, manifest=None, overrides=None): return content +def seed_audio_references(store, task, rules, result, overrides): + """Seed Audio takes one image or several voice samples, never both.""" + total_ms = 0 + for data, meta, source_kind in references(store, task['projectId'], task['referenceIds'], overrides): + entry = {'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': source_kind, 'transmission': 'content'} + if source_kind == 'image': + mime = image_type(data) + if mime not in {'image/png', 'image/jpeg', 'image/webp'} or len(data) > rules['imageBytes']: + raise ProjectError(f'“{meta["name"]}”不能作为参考图片:需为 PNG、JPEG 或 WEBP,且不超过大小限制。', 422, code='audio_reference_image') + if len(result['images']) >= rules['maxImages']: + raise ProjectError(f'Seed Audio 1.5 最多引用 {rules["maxImages"]} 张图片。', 422, code='audio_reference_count') + result['images'].append(data_uri(data, mime)) + result['imageRoles'].append('reference_image') + result['manifest'].append({**entry, 'role': 'reference_image'}) + elif source_kind == 'audio': + if meta['type'] not in {'audio/wav', 'audio/x-wav', 'audio/mpeg'} or len(data) > SEED_AUDIO_REFERENCE_BYTES: + raise ProjectError('参考音频需为不超过 15 MB 的 WAV 或 MP3。', 422, code='audio_reference_audio') + duration = meta.get('durationMs') + low, high = SEED_AUDIO_REFERENCE_MS + if duration is None or not low <= duration <= high: + raise ProjectError(f'参考音频需为 {low // 1000}—{high // 1000} 秒。', 422, code='audio_reference_audio') + total_ms += duration + if len(result['audios']) >= rules['maxAudios'] or total_ms > SEED_AUDIO_REFERENCE_TOTAL_MS: + raise ProjectError(f'参考音频最多 {rules["maxAudios"]} 段、合计不超过 {SEED_AUDIO_REFERENCE_TOTAL_MS // 1000} 秒。', 422, code='audio_reference_count') + result['audios'].append(data_uri(data, 'audio/wav' if meta['type'] == 'audio/x-wav' else meta['type'])) + result['manifest'].append({**entry, 'role': 'reference_audio'}) + else: + raise ProjectError(f'“{meta["name"]}”:Seed Audio 1.5 暂不接受视频参考。', 422, code='audio_reference_video') + if result['images'] and result['audios']: + raise ProjectError('Seed Audio 1.5 的图片参考与音频参考不能同时使用。', 422, code='audio_reference_mix') + return result + + def continuation_source(store, project_id, meta, config): """Remote job ID of an earlier clip this same H3 service generated; its latents stay server-side.""" message = f'“{meta["name"]}”不能接续:需引用由当前 vLLM-Omni H3 服务生成并已完成的视频,上传或其他模型生成的视频不能接续。' @@ -114,6 +147,8 @@ def generation_references(store, task, config, *, complete=True, overrides=None) if rules['profile'] == 'zhipu-speech': raise ProjectError('GLM-TTS 不支持参考素材,请直接填写朗读文本并选择音色。', 422, code='zhipu_speech_reference') raise ProjectError('MOSS 语音生成不支持参考素材,请直接填写朗读文本和音色 ID。', 422, code='moss_speech_reference') + if rules.get('referencesAllowed'): + return seed_audio_references(store, task, rules, result, overrides) # Historical context remains recorded; it is never appended to speech. result['manifest'] = [{'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': source_kind, 'transmission': 'context_only'} for _, meta, source_kind in references(store, task['projectId'], task['referenceIds'], overrides)] diff --git a/packages/core/src/opendirector/integrations/seed_audio.py b/packages/core/src/opendirector/integrations/seed_audio.py new file mode 100644 index 000000000..cdd6d95b8 --- /dev/null +++ b/packages/core/src/opendirector/integrations/seed_audio.py @@ -0,0 +1,35 @@ +"""Volcengine Ark Seed Audio 1.5 content generation.""" + +from opendirector.domain.rule_facts import SEED_AUDIO_MODEL_PREFIX as MODEL_PREFIX + +def is_seed_audio(model_id): + return isinstance(model_id, str) and model_id.startswith(MODEL_PREFIX) + + +def request_body(config, prompt, parameters, images=(), audios=()): + """The whole outgoing request, derived from the accepted adapter parameters.""" + content = [{'type': 'text', 'text': prompt}] + content.extend({'type': 'image_url', 'role': 'reference_image', 'image_url': {'url': image}} for image in images) + content.extend({'type': 'audio_url', 'role': 'reference_audio', 'audio_url': {'url': audio}} for audio in audios) + body = {'model': config['modelId'], 'content': content, + 'output_format': parameters.get('output_format') or 'mp3'} + audio = {key: parameters[key] for key in + ('sample_rate', 'speech_rate', 'loudness_rate', 'pitch_rate') + if parameters.get(key) is not None} + if audio: + body['audio_config'] = audio + return body + + +def artifact_urls(value): + """Artifact URLs in response order; the first one is the primary result.""" + audios = value['content']['audios'] + if not isinstance(audios, list) or not audios: + raise ValueError('Seed Audio returned no audio artifact') + urls = [] + for audio in audios: + url = audio.get('url') if isinstance(audio, dict) else None + if not isinstance(url, str) or not url: + raise ValueError('Seed Audio artifact has no URL') + urls.append(url) + return tuple(urls) diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index d574b8328..434cb29f9 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -16,6 +16,8 @@ from opendirector.integrations.chat_completions import ChatCompletions, chat_payload from opendirector.integrations.reference_inputs import generation_references, request_size from opendirector.integrations.generation_errors import checked, protocol_failure, provider_failure, transport_failure +from opendirector.integrations.seed_audio import (artifact_urls as seed_audio_artifacts, is_seed_audio, + request_body as seed_audio_body) from opendirector.media.probe import require_ffprobe @@ -76,6 +78,11 @@ async def resume_result(self, config, suffix, url, *, public_only=False): def validate(self, kind, config): if kind in {"video", "audio"}: require_ffprobe() + if kind == "audio" and is_seed_audio(config["modelId"]): + if "/api/plan/" in urlsplit(config["url"]).path: + raise ProjectError("Seed Audio 1.5 需要方舟内容生成接口地址(…/api/v3),请使用对应的模型预设。", + 422, code="seed_audio_base_url") + return if kind == "audio" and config["modelId"] not in {"doubao-seed-tts-2.0", "seed-tts-2.0"}: raise ProjectError("当前音频生成支持火山 Agent Plan 的 doubao-seed-tts-2.0。", 409) @@ -198,6 +205,18 @@ async def query(): if value.get("status") not in {"queued", "running", "submitted"}: raise protocol_failure(stage) await asyncio.sleep(self.poll_interval) + if kind == "audio" and is_seed_audio(config["modelId"]): + payload = seed_audio_body(config, prompt, task["parameters"], + prepared['images'], prepared['audios']) + request_size(payload, prepared['rules']['requestBytes']) + async with client.stream("POST", endpoint(config["url"], "/contents/generations"), + headers=headers, json=payload) as response: + value = json.loads(await bounded(response, stage=stage, secrets=secrets)) + stage = 'download' + urls = seed_audio_artifacts(value) + if result_ready: + await result_ready(payload['output_format'], urls[0]) + return payload['output_format'], await self._download(client, urls[0], secrets=secrets) if kind == "audio": url = endpoint(config["url"], "/tts/unidirectional") headers = {"X-Api-Key": config["apiKey"], "X-Api-Resource-Id": "seed-tts-2.0", "X-Api-Request-Id": str(uuid4())} diff --git a/src/backend/rules.ts b/src/backend/rules.ts index cea000706..10c2c9d66 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -60,6 +60,9 @@ export interface InputRules { aspectRatios?: string[] | null; frameRoles?: ("first_frame" | "last_frame")[] | null; audioReferenceStandalone?: boolean | null; + audioTasks?: CreationInputRules["audioTasks"]; + outputFormats?: CreationInputRules["outputFormats"]; + sampleRates?: CreationInputRules["sampleRates"]; generateAudioOptions?: boolean[] | null; imageOutputs?: { aspectRatio: string; size: string }[]; imageQualities?: CreationInputRules["imageQualities"]; @@ -152,11 +155,14 @@ export function serviceAudioSettings( // that capability exists. Keeping the selection would block generation with // "the voice belongs to another service" and leave no control to replace it, // so drop it here rather than waiting for a model switch to do the same. - const unusable = !config.inputRules.voiceLibrary && Boolean(settings.voiceSelection); + const unified = Boolean(config.inputRules.audioTasks?.length); + const unusable = + unified || + (!config.inputRules.voiceLibrary && Boolean(settings.voiceSelection)); return { ...settings, audioCreationType: music ? "music" : "audio", - audioMode: "tts", + audioMode: unified ? "unified" : "tts", ...(unusable ? { voiceSelection: undefined, voiceName: undefined } : {}), ...(music && !(seconds >= MUSIC_SECONDS.min && seconds <= MUSIC_SECONDS.max) ? { durationSeconds: MUSIC_SECONDS.initial } @@ -227,7 +233,7 @@ export function backendReferenceIssue( const kind = node.data.kind; const rules = config.inputRules; const unusedInReading = - settings.mode === "audio" && !isMusicModel(config) + settings.mode === "audio" && !isMusicModel(config) && !rules.referencesAllowed ? tNow("generation.issue.audioModeReference") : null; if ( @@ -708,7 +714,9 @@ export function backendBlocker( } else if ( settings.mode === "audio" && ((settings.audioCreationType && settings.audioCreationType !== "audio") || - (settings.audioMode && settings.audioMode !== "tts")) + (settings.audioMode && + settings.audioMode !== "tts" && + !config.inputRules.audioTasks?.length)) ) return tNow("errors.rules.speechOnly"); if ( diff --git a/src/canvas/NodeComposer.tsx b/src/canvas/NodeComposer.tsx index 847a153bb..234d62b29 100644 --- a/src/canvas/NodeComposer.tsx +++ b/src/canvas/NodeComposer.tsx @@ -406,7 +406,10 @@ export function NodeComposer({ ? Boolean(config && isMusicModel(config)) : settings.audioCreationType === "music"); const reading = - mode === "audio" && !music && (backend || settings.audioMode === "tts"); + mode === "audio" && + !music && + !config?.inputRules.audioTasks?.length && + (backend || settings.audioMode === "tts"); // YuE2-style music models can follow one connected recording. const musicReferences = music && Boolean(config?.inputRules.allowedKinds.includes("audio")); @@ -1229,12 +1232,22 @@ export function NodeComposer({ - + {/* A unified adapter publishes its operations and rejects + text reading outright, so do not offer it there. */} + {!config?.inputRules.audioTasks?.length && ( + + )} )} )} - {mode === "audio" && backend && !music && !voiceLibrary && ( + {mode === "audio" && + backend && + !music && + !voiceLibrary && + !config?.inputRules.audioTasks?.length && ( = { "MiniMax 官方语音": "MiniMax Official Speech", "MOSS 开放平台": "MOSS Open Platform", "火山方舟 / Agent Plan": "Volcano Ark / Agent Plan", + "火山方舟 / 内容生成": "Volcano Ark / Content Generation", "vLLM-Omni 图片接口": "vLLM-Omni image API", "vLLM-Omni 语音合成接口": "vLLM-Omni speech synthesis API", "vLLM-Omni 音乐生成接口": "vLLM-Omni music generation API", @@ -301,6 +302,17 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [ audio: ["seed-tts-2.0"], }, }, + { + id: "ark-content", + logoOrganization: "ByteDance-Seed", + name: "火山方舟 / 内容生成", + kinds: ["audio"], + url: "https://ark.cn-beijing.volces.com/api/v3", + protocol: "volcengine", + connectionType: "api", + authMode: "bearer", + modelsByKind: { audio: ["doubao-seed-audio-1-5-261128"] }, + }, ...( [ ["vllm-omni-image", "vLLM-Omni 图片接口", "openai", ["image"]], @@ -336,13 +348,17 @@ export const PROVIDER_PRESETS: ProviderPreset[] = [ ]; export function providerPresetFor(model: ModelConfig): string { - const explicit = PROVIDER_PRESETS.find( + const url = model.url.replace(/\/+$/, ""); + const candidates = PROVIDER_PRESETS.filter( (preset) => preset.connectionType === "api" && preset.protocol !== "openai" && preset.protocol === model.protocol && preset.kinds.includes(model.kind), ); + const explicit = + candidates.find((preset) => preset.url.replace(/\/+$/, "") === url) ?? + candidates[0]; if (explicit) return explicit.id; const deployed = PROVIDER_PRESETS.find( (preset) => @@ -352,7 +368,6 @@ export function providerPresetFor(model: ModelConfig): string { ); if (deployed && model.connectionType === "self_hosted") return deployed.id; if (model.connectionType === "self_hosted") return "custom"; - const url = model.url.replace(/\/+$/, ""); return ( PROVIDER_PRESETS.find( (preset) => diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 90c059d80..04a8f7833 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -1269,6 +1269,64 @@ "description": "Audio samples per second.", "title": "Samplerate" }, + "taskType": { + "anyOf": [ + { + "enum": [ + "text2audio", + "reference", + "separation", + "dubbing" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Audio operation fixed when the job was accepted.", + "title": "Tasktype" + }, + "speechRate": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Speaking-rate offset fixed when the job was accepted.", + "title": "Speechrate" + }, + "loudnessRate": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Loudness offset fixed when the job was accepted.", + "title": "Loudnessrate" + }, + "pitchRate": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Pitch offset fixed when the job was accepted.", + "title": "Pitchrate" + }, "creationType": { "default": "audio", "description": "Speech or music creation mode.", @@ -1553,6 +1611,73 @@ "default": null, "description": "Music with one audio reference: cap the length at the reference length (unset follows it) instead of durationSeconds", "title": "Durationfromreference" + }, + "taskType": { + "default": "text2audio", + "description": "Audio operation; the adapter derives outgoing reference roles from it.", + "enum": [ + "text2audio", + "reference", + "separation", + "dubbing" + ], + "title": "Tasktype", + "type": "string" + }, + "speechRate": { + "default": 0, + "description": "Speaking-rate percentage offset.", + "maximum": 100, + "minimum": -50, + "title": "Speechrate", + "type": "integer" + }, + "loudnessRate": { + "default": 0, + "description": "Loudness percentage offset.", + "maximum": 100, + "minimum": -50, + "title": "Loudnessrate", + "type": "integer" + }, + "pitchRate": { + "default": 0, + "description": "Pitch offset in semitones.", + "maximum": 12, + "minimum": -12, + "title": "Pitchrate", + "type": "integer" + }, + "outputFormat": { + "default": "mp3", + "description": "Requested audio container format.", + "enum": [ + "mp3", + "wav" + ], + "title": "Outputformat", + "type": "string" + }, + "sampleRate": { + "anyOf": [ + { + "enum": [ + 8000, + 16000, + 24000, + 32000, + 44100, + 48000 + ], + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Requested audio samples per second.", + "title": "Samplerate" } }, "title": "AudioParameters", @@ -4531,6 +4656,15 @@ "storage_unavailable", "submission_unknown", "provider_error", + "audio_music_unsupported", + "audio_mode_required", + "audio_task_unsupported", + "seed_audio_base_url", + "audio_reference_image", + "audio_reference_audio", + "audio_reference_count", + "audio_reference_mix", + "audio_reference_video", "moss_speech_text", "moss_speech_voice", "moss_speech_reference", @@ -8542,6 +8676,43 @@ "description": "Whether audio-only references are supported.", "title": "Audioreferencestandalone" }, + "audioTasks": { + "default": [], + "description": "Audio operations accepted in unified mode; empty keeps text reading only.", + "items": { + "enum": [ + "text2audio", + "reference", + "separation", + "dubbing" + ], + "type": "string" + }, + "title": "Audiotasks", + "type": "array" + }, + "outputFormats": { + "default": [], + "description": "Accepted audio container formats in unified mode.", + "items": { + "enum": [ + "mp3", + "wav" + ], + "type": "string" + }, + "title": "Outputformats", + "type": "array" + }, + "sampleRates": { + "default": [], + "description": "Accepted audio sample rates in unified mode.", + "items": { + "type": "integer" + }, + "title": "Samplerates", + "type": "array" + }, "generateAudioOptions": { "anyOf": [ { @@ -21171,6 +21342,64 @@ "description": "Audio samples per second.", "title": "Samplerate" }, + "taskType": { + "anyOf": [ + { + "enum": [ + "text2audio", + "reference", + "separation", + "dubbing" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Audio operation fixed when the job was accepted.", + "title": "Tasktype" + }, + "speechRate": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Speaking-rate offset fixed when the job was accepted.", + "title": "Speechrate" + }, + "loudnessRate": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Loudness offset fixed when the job was accepted.", + "title": "Loudnessrate" + }, + "pitchRate": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Pitch offset fixed when the job was accepted.", + "title": "Pitchrate" + }, "creationType": { "default": "audio", "description": "Speech or music creation mode.", @@ -21465,6 +21694,73 @@ "default": null, "description": "Music with one audio reference: cap the length at the reference length (unset follows it) instead of durationSeconds", "title": "Durationfromreference" + }, + "taskType": { + "default": "text2audio", + "description": "Audio operation; the adapter derives outgoing reference roles from it.", + "enum": [ + "text2audio", + "reference", + "separation", + "dubbing" + ], + "title": "Tasktype", + "type": "string" + }, + "speechRate": { + "default": 0, + "description": "Speaking-rate percentage offset.", + "maximum": 100, + "minimum": -50, + "title": "Speechrate", + "type": "integer" + }, + "loudnessRate": { + "default": 0, + "description": "Loudness percentage offset.", + "maximum": 100, + "minimum": -50, + "title": "Loudnessrate", + "type": "integer" + }, + "pitchRate": { + "default": 0, + "description": "Pitch offset in semitones.", + "maximum": 12, + "minimum": -12, + "title": "Pitchrate", + "type": "integer" + }, + "outputFormat": { + "default": "mp3", + "description": "Requested audio container format.", + "enum": [ + "mp3", + "wav" + ], + "title": "Outputformat", + "type": "string" + }, + "sampleRate": { + "anyOf": [ + { + "enum": [ + 8000, + 16000, + 24000, + 32000, + 44100, + 48000 + ], + "type": "integer" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Requested audio samples per second.", + "title": "Samplerate" } }, "required": [ @@ -24519,6 +24815,15 @@ "storage_unavailable", "submission_unknown", "provider_error", + "audio_music_unsupported", + "audio_mode_required", + "audio_task_unsupported", + "seed_audio_base_url", + "audio_reference_image", + "audio_reference_audio", + "audio_reference_count", + "audio_reference_mix", + "audio_reference_video", "moss_speech_text", "moss_speech_voice", "moss_speech_reference", @@ -28677,6 +28982,43 @@ "description": "Whether audio-only references are supported.", "title": "Audioreferencestandalone" }, + "audioTasks": { + "default": [], + "description": "Audio operations accepted in unified mode; empty keeps text reading only.", + "items": { + "enum": [ + "text2audio", + "reference", + "separation", + "dubbing" + ], + "type": "string" + }, + "title": "Audiotasks", + "type": "array" + }, + "outputFormats": { + "default": [], + "description": "Accepted audio container formats in unified mode.", + "items": { + "enum": [ + "mp3", + "wav" + ], + "type": "string" + }, + "title": "Outputformats", + "type": "array" + }, + "sampleRates": { + "default": [], + "description": "Accepted audio sample rates in unified mode.", + "items": { + "type": "integer" + }, + "title": "Samplerates", + "type": "array" + }, "generateAudioOptions": { "anyOf": [ { diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 5bc0d437d..89e0001af 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -131,6 +131,10 @@ export interface AudioExecutionInput extends ContractInput { readonly speaker?: string | null; readonly format: "mp3" | "wav"; readonly sampleRate?: number | null; + readonly taskType?: "text2audio" | "reference" | "separation" | "dubbing" | null; + readonly speechRate?: number | null; + readonly loudnessRate?: number | null; + readonly pitchRate?: number | null; readonly creationType?: "audio" | "music"; readonly instrumental?: boolean; readonly maxDurationSeconds?: number | null; @@ -153,6 +157,12 @@ export interface AudioParametersInput extends ContractInput { readonly durationSeconds?: number | null; readonly scoreMode?: "melody" | "full"; readonly durationFromReference?: boolean | null; + readonly taskType?: "text2audio" | "reference" | "separation" | "dubbing"; + readonly speechRate?: number; + readonly loudnessRate?: number; + readonly pitchRate?: number; + readonly outputFormat?: "mp3" | "wav"; + readonly sampleRate?: 8000 | 16000 | 24000 | 32000 | 44100 | 48000 | null; } export interface AvailabilityCatalogInput extends ContractInput { @@ -497,7 +507,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -850,6 +860,9 @@ export interface InputRulesInput extends ContractInput { readonly aspectRatios?: ReadonlyArray | null; readonly frameRoles?: ReadonlyArray<"first_frame" | "last_frame"> | null; readonly audioReferenceStandalone?: boolean | null; + readonly audioTasks?: ReadonlyArray<"text2audio" | "reference" | "separation" | "dubbing">; + readonly outputFormats?: ReadonlyArray<"mp3" | "wav">; + readonly sampleRates?: ReadonlyArray; readonly generateAudioOptions?: ReadonlyArray | null; } @@ -2169,6 +2182,10 @@ export interface AudioExecution extends Contract { readonly speaker: string | null; readonly format: "mp3" | "wav"; readonly sampleRate: number | null; + readonly taskType?: "text2audio" | "reference" | "separation" | "dubbing" | null; + readonly speechRate?: number | null; + readonly loudnessRate?: number | null; + readonly pitchRate?: number | null; readonly creationType?: "audio" | "music"; readonly instrumental?: boolean; readonly maxDurationSeconds?: number | null; @@ -2191,6 +2208,12 @@ export interface AudioParameters extends Contract { readonly durationSeconds?: number | null; readonly scoreMode?: "melody" | "full"; readonly durationFromReference?: boolean | null; + readonly taskType?: "text2audio" | "reference" | "separation" | "dubbing"; + readonly speechRate?: number; + readonly loudnessRate?: number; + readonly pitchRate?: number; + readonly outputFormat?: "mp3" | "wav"; + readonly sampleRate?: 8000 | 16000 | 24000 | 32000 | 44100 | 48000 | null; } export interface AvailabilityCatalog extends Contract { @@ -2535,7 +2558,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId: string | null; readonly field: string | null; @@ -2888,6 +2911,9 @@ export interface InputRules extends Contract { readonly aspectRatios?: ReadonlyArray | null; readonly frameRoles?: ReadonlyArray<"first_frame" | "last_frame"> | null; readonly audioReferenceStandalone?: boolean | null; + readonly audioTasks?: ReadonlyArray<"text2audio" | "reference" | "separation" | "dubbing">; + readonly outputFormats?: ReadonlyArray<"mp3" | "wav">; + readonly sampleRates?: ReadonlyArray; readonly generateAudioOptions?: ReadonlyArray | null; } diff --git a/tests/arkProviderPreset.test.ts b/tests/arkProviderPreset.test.ts index d4babb8ce..dd42bcb54 100644 --- a/tests/arkProviderPreset.test.ts +++ b/tests/arkProviderPreset.test.ts @@ -1,6 +1,9 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { PROVIDER_PRESETS } from "../src/canvas/providerPresets.ts"; +import { + PROVIDER_PRESETS, + providerPresetFor, +} from "../src/canvas/providerPresets.ts"; const ark = PROVIDER_PRESETS.find((preset) => preset.id === "ark")!; @@ -31,3 +34,35 @@ test("picking Ark preselects both Seedance families", () => { test("picking Ark preselects the voice resource id", () => { assert.deepEqual(ark.modelsByKind?.audio, ["seed-tts-2.0"]); }); + +test("Seed Audio 1.5 has its own content-generation preset", () => { + const content = PROVIDER_PRESETS.find((preset) => preset.id === "ark-content")!; + assert.equal(content.url, "https://ark.cn-beijing.volces.com/api/v3"); + assert.equal(content.protocol, "volcengine"); + assert.deepEqual(content.kinds, ["audio"]); + assert.deepEqual(content.modelsByKind?.audio, ["doubao-seed-audio-1-5-261128"]); + assert.notEqual(content.url, ark.url); +}); + +test("the base URL decides which Ark preset a connection belongs to", () => { + const model = (url: string) => + ({ + id: "m1", + projectId: null, + kind: "audio", + protocol: "volcengine", + connectionType: "api", + authMode: "bearer", + url, + modelId: "seed-tts-2.0", + inputRules: {}, + }) as unknown as Parameters[0]; + assert.equal( + providerPresetFor(model("https://ark.cn-beijing.volces.com/api/v3")), + "ark-content", + ); + assert.equal( + providerPresetFor(model("https://ark.cn-beijing.volces.com/api/plan/v3")), + "ark", + ); +}); diff --git a/tests/backendRules.test.ts b/tests/backendRules.test.ts index 731dda70d..4de0a4c92 100644 --- a/tests/backendRules.test.ts +++ b/tests/backendRules.test.ts @@ -491,3 +491,38 @@ test("structure control sends exactly one video as the control and keeps it out ["reference"], ); }); + +test("a unified speech model defaults to the unified mode and keeps it", () => { + const unified = { + ...config("audio", { + profile: "seed-audio", + allowedKinds: [], + maxImages: 0, + maxVideos: 0, + maxAudios: 0, + videoModes: [], + audioTasks: ["text2audio"], + outputFormats: ["mp3", "wav"], + }), + protocol: "volcengine" as const, + modelId: "doubao-seed-audio-1-5-261128", + }; + const settings = { + ...generationDefaults("audio"), + modelConfigId: unified.id, + prompt: "“你好,这里是 Seed Audio 的试音。”", + audioMode: "tts" as const, + }; + const normalized = serviceGenerationSettings(settings, unified); + assert.equal(normalized.audioMode, "unified"); + assert.equal(normalized.voiceName, undefined); + assert.equal(backendBlocker(normalized, [], [unified]), null); + const reading = { + ...unified, + inputRules: { ...unified.inputRules, profile: "tts", audioTasks: [] }, + }; + assert.match( + backendBlocker({ ...settings, audioMode: "unified" }, [], [reading])!, + /文本朗读/, + ); +}); diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py new file mode 100644 index 000000000..50bf2a78b --- /dev/null +++ b/tests/test_seed_audio.py @@ -0,0 +1,240 @@ +"""Seed Audio 1.5: verified request shape, accepted intent and one durable job. + +The live-service facts behind these expectations are recorded in +``docs/development/seed-audio-1-5-probe.md``. +""" +import asyncio +import json +import subprocess +from uuid import UUID + +import httpx +import pytest + +from opendirector.domain.creation.generation import AudioGenerationSpec, validate_generation +from opendirector.domain.creation.models import InputRules, ModelConfigPublic +from opendirector.domain.input_rules import input_rules +from opendirector.domain.projects import ProjectError +from opendirector.integrations.seed_audio import artifact_urls, request_body +from opendirector.integrations.volcengine import VolcengineGeneration +from test_creation_contracts import entity, model as public_model +from test_creation_canvas_service import project # noqa: F401 (pytest fixture) +from test_creation_generation_service import anyio_backend # noqa: F401 (pytest fixture) +from test_creation_parameters import done, setup, submit + + +pytestmark = pytest.mark.cpu +MODEL = 'doubao-seed-audio-1-5-261128' +MODEL_ID = UUID(int=20) +CONTENT_BASE = 'https://ark.cn-beijing.volces.com/api/v3' +PLAN_BASE = 'https://ark.cn-beijing.volces.com/api/plan/v3' + + +def config(url=CONTENT_BASE, model=MODEL): + return {'kind': 'audio', 'modelId': model, 'url': url, 'protocol': 'volcengine', + 'connectionType': 'api', 'authMode': 'bearer', 'name': 'Seed Audio 1.5'} + + +def audio_spec(**parameters): + fields = {'mode': 'unified', 'creationType': 'audio'} + fields.update(parameters) + return AudioGenerationSpec(**entity(66, kind='audio', modelConfigId=MODEL_ID, + prompt='“你好,这里是 Seed Audio 的试音。”', parameters=fields)) + + +def seed_model(url=CONTENT_BASE): + return public_model('audio', protocol='volcengine', url=url, modelId=MODEL, connectionType='api', authMode='bearer') + + +def test_adapter_publishes_only_the_verified_operation(): + rules = InputRules.model_validate(input_rules(config())) + assert rules.profile == 'seed-audio' + assert rules.audioTasks == ('text2audio',) + assert rules.allowedKinds == ('image', 'audio') and rules.maxImages == 1 and rules.maxAudios == 6 + assert rules.referencesAllowed is True + assert rules.maxPromptCharacters == 10000 + assert rules.outputFormats == ('mp3', 'wav') + assert rules.sampleRates == (8000, 16000, 24000, 32000, 44100, 48000) + + +def test_text_reading_services_keep_the_reading_profile(): + assert input_rules(config(url=PLAN_BASE, model='seed-tts-2.0'))['profile'] == 'tts' + assert input_rules({**config(), 'protocol': 'openai'})['profile'] == 'tts' + + +@pytest.mark.parametrize('format_name', ['mp3', 'wav']) +@pytest.mark.parametrize('rate', [8000, 16000, 24000, 32000, 44100, 48000]) +def test_every_published_option_is_accepted_by_the_contract(format_name, rate): + spec = audio_spec(outputFormat=format_name, sampleRate=rate) + assert spec.parameters.outputFormat == format_name and spec.parameters.sampleRate == rate + rules = InputRules.model_validate(input_rules(config())) + assert format_name in rules.outputFormats and rate in rules.sampleRates + + +def test_request_body_carries_only_the_accepted_prosody_controls(): + body = request_body(config(), '台词', {'output_format': 'wav', 'sample_rate': 48000, + 'speech_rate': -10, 'loudness_rate': 5, 'pitch_rate': 2}) + assert body == {'model': MODEL, 'content': [{'type': 'text', 'text': '台词'}], + 'output_format': 'wav', + 'audio_config': {'sample_rate': 48000, 'speech_rate': -10, + 'loudness_rate': 5, 'pitch_rate': 2}} + assert request_body(config(), '台词', {'output_format': 'mp3'}) == { + 'model': MODEL, 'content': [{'type': 'text', 'text': '台词'}], 'output_format': 'mp3'} + + +def test_incomplete_artifact_lists_are_rejected(): + with pytest.raises(ValueError): + artifact_urls({'content': {'audios': []}}) + with pytest.raises(ValueError): + artifact_urls({'content': {'audios': [{}]}}) + with pytest.raises(KeyError): + artifact_urls({'content': {}}) + assert artifact_urls({'content': {'audios': [{'url': 'https://a/1.mp3'}, + {'url': 'https://a/2.mp3'}]}}) == ('https://a/1.mp3', 'https://a/2.mp3') + + +def test_agent_plan_base_is_refused_before_any_request(): + provider = VolcengineGeneration(None, httpx.MockTransport(lambda request: pytest.fail('must not request'))) + with pytest.raises(ProjectError) as caught: + provider.validate('audio', {**config(url=PLAN_BASE), 'apiKey': 'key'}) + assert caught.value.code == 'seed_audio_base_url' + provider.validate('audio', {**config(), 'apiKey': 'key'}) + + +def test_unified_mode_is_accepted_only_for_the_unified_profile(): + validate_generation(audio_spec(), seed_model()) + for parameters, code in [({'mode': 'tts'}, 'audio_mode_required'), + ({'creationType': 'music'}, 'audio_music_unsupported'), + ({'taskType': 'dubbing'}, 'audio_task_unsupported')]: + with pytest.raises(ProjectError) as caught: + validate_generation(audio_spec(**parameters), seed_model()) + assert caught.value.code == code + reading = public_model('audio', protocol='volcengine', url=PLAN_BASE, modelId='seed-tts-2.0') + with pytest.raises(ValueError, match='文本朗读'): + validate_generation(audio_spec(), reading) + + +@pytest.mark.anyio +async def test_unified_text_to_audio_reaches_the_content_api_and_reopens(project): + store, pid, _ = project + audio = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', + 'sine=frequency=440:sample_rate=44100', '-t', '0.3', + '-threads', '1', '-f', 'mp3', 'pipe:1'], + capture_output=True, check=True).stdout + posted = [] + + def handler(request): + if request.method == 'GET': + return httpx.Response(200, content=audio, headers={'content-type': 'audio/mpeg'}) + posted.append((request.url.path, json.loads(request.content))) + return httpx.Response(200, json={'id': '0217', 'model': MODEL, 'output_format': 'mp3', + 'content': {'audios': [{'url': 'http://fixture.invalid/api/v3/result.mp3'}]}, + 'usage': {'duration_ms': 3000, 'final_duration_ms': 300}}) + + runner, target, spec_id = setup( + project, 'audio', dict(mode='unified', creationType='audio', speechRate=8, sampleRate=44100, + outputFormat='mp3', taskType='text2audio'), + handler, protocol='volcengine', model=MODEL, url=CONTENT_BASE) + try: + _, receipt = await submit(project, runner, target, spec_id) + assert receipt.status == 'accepted', receipt + await done(runner) + snapshot = store.snapshot(pid) + job = snapshot.jobs[-1] + assert job.status == 'succeeded', job.errorDetails + assert posted == [('/api/v3/contents/generations', { + 'model': MODEL, 'content': [{'type': 'text', 'text': 'Make an output'}], + 'output_format': 'mp3', 'audio_config': {'sample_rate': 44100, 'speech_rate': 8}})] + assert job.execution.taskType == 'text2audio' + assert job.execution.speechRate == 8 and job.execution.format == 'mp3' + assert job.inputSnapshot.spec.parameters.mode == 'unified' + assert next(a for a in snapshot.assets if a.id == job.asset.assetId).kind == 'audio' + assert 'fixture-key' not in job.model_dump_json() + finally: + await runner.close() + + +def reference_store(tmp_path): + from PIL import Image + import io + import wave + from generation_helpers import new_project + from opendirector.application.creation_generation import CreationGeneration + from opendirector.application.creation_tool_assets import CreationToolAssets + from opendirector.infrastructure.local_projects import LocalProjects + from opendirector.infrastructure.model_configs import ModelConfigs + + projects, pid, session = new_project(tmp_path, 'Seed Audio 参考') + store = CreationGeneration(projects, ModelConfigs(tmp_path)).store + canvas = CreationToolAssets(projects) + buffer = io.BytesIO(); Image.new('RGB', (512, 512), 'teal').save(buffer, 'PNG') + image = canvas.import_file(str(pid), str(UUID(int=31)), '场景.png', buffer.getvalue(), session) + def voice(seconds, name): + buffer = io.BytesIO() + with wave.open(buffer, 'wb') as wav: + wav.setparams((1, 2, 24000, 0, 'NONE', 'not compressed')) + wav.writeframes(b'\0\0' * 24000 * seconds) + return canvas.import_file(str(pid), str(UUID(int=32 + seconds)), name, buffer.getvalue(), session) + return store, str(pid), image, voice(3, '样音.wav'), voice(1, '过短.wav') + + +def reference_task(owner, refs, **changes): + from opendirector.integrations.reference_inputs import generation_references + return generation_references(store_task(owner, refs), config(), **changes) + + +def store_task(owner, refs): + return {'kind': 'audio', 'projectId': owner, 'prompt': '“按这个音色说一句。”', + 'referenceIds': [asset['id'] for asset in refs], + 'parameters': {'mode': 'unified', 'creationType': 'audio'}} + + +def prepared(store, owner, refs): + from opendirector.integrations.reference_inputs import generation_references + return generation_references(store, store_task(owner, refs), config()) + + +def test_one_image_reference_travels_as_a_reference_image(tmp_path): + store, owner, image, _, _ = reference_store(tmp_path) + ready = prepared(store, owner, [image]) + assert len(ready['images']) == 1 and ready['audios'] == [] + assert [entry['role'] for entry in ready['manifest']] == ['reference_image'] + body = request_body(config(), ready['prompt'], {'output_format': 'mp3'}, ready['images'], ready['audios']) + assert body['content'][1]['type'] == 'image_url' + assert body['content'][1]['role'] == 'reference_image' + assert body['content'][1]['image_url']['url'].startswith('data:image/png;base64,') + + +def test_voice_references_travel_as_reference_audio(tmp_path): + store, owner, _, voice, _ = reference_store(tmp_path) + ready = prepared(store, owner, [voice, voice]) + assert len(ready['audios']) == 1 and ready['images'] == [] + assert {entry['role'] for entry in ready['manifest']} == {'reference_audio'} + body = request_body(config(), ready['prompt'], {'output_format': 'mp3'}, ready['images'], ready['audios']) + assert [item['type'] for item in body['content']] == ['text', 'audio_url'] + assert body['content'][1]['audio_url']['url'].startswith('data:audio/wav;base64,') + + +def test_image_and_voice_references_cannot_be_mixed(tmp_path): + store, owner, image, voice, _ = reference_store(tmp_path) + with pytest.raises(ProjectError) as failure: + prepared(store, owner, [image, voice]) + assert failure.value.code == 'audio_reference_mix' + + +def test_voice_references_must_be_two_to_thirty_seconds(tmp_path): + store, owner, _, _, short = reference_store(tmp_path) + with pytest.raises(ProjectError) as failure: + prepared(store, owner, [short]) + assert failure.value.code == 'audio_reference_audio' + + +def test_video_references_stay_unsupported(tmp_path): + store, owner, _, _, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=40)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': 5000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + with pytest.raises(ProjectError) as failure: + prepared(store, owner, [video]) + assert failure.value.code == 'audio_reference_video' From 161fb0488cc06127831336f909cae5b65f283e0d Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:02:08 +0800 Subject: [PATCH 02/58] [feat] storage: presign TOS objects so the provider can fetch project media Ark accepts only `http(s)://` and `tos://` for `video_url`, and a bare `tos://` key is refused with `AccessDenied` unless the account grants it service access. A presigned URL keeps the object private and still lets the service read it, so dubbing, translation and subtitle work can send a project video without publishing it. TOS4 signing is implemented with the standard library, so the container gains no dependency for what is a few HMAC rounds. Verified against the live bucket: a 68378-byte upload returned 200, the presigned URL served the same bytes, and Ark accepted it for `role=dubbing_video` with `target_language=zh`, returning a dubbed video, an extracted audio track and one SRT subtitle. Refs #650 --- .../opendirector/integrations/tos_transfer.py | 122 ++++++++++++++++++ tests/test_tos_transfer.py | 100 ++++++++++++++ 2 files changed, 222 insertions(+) create mode 100644 packages/core/src/opendirector/integrations/tos_transfer.py create mode 100644 tests/test_tos_transfer.py diff --git a/packages/core/src/opendirector/integrations/tos_transfer.py b/packages/core/src/opendirector/integrations/tos_transfer.py new file mode 100644 index 000000000..9c8d65af5 --- /dev/null +++ b/packages/core/src/opendirector/integrations/tos_transfer.py @@ -0,0 +1,122 @@ +"""Object storage transfer for media the provider must fetch by URL.""" +from __future__ import annotations + +import hashlib +import hmac +from datetime import datetime, timedelta, timezone +from urllib.parse import quote, urlsplit + +import httpx + +from .http_settings import trust_environment + +ALGORITHM = 'TOS4-HMAC-SHA256' +SERVICE = 'tos' +UNSIGNED = 'UNSIGNED-PAYLOAD' + + +class TransferError(RuntimeError): + def __init__(self, code, detail=''): + super().__init__(detail or code) + self.code = code + + +def _sign(key, message): + return hmac.new(key, message.encode(), hashlib.sha256).digest() + + +def _signing_key(secret, date, region): + key = _sign(secret.encode(), date) + key = _sign(key, region) + key = _sign(key, SERVICE) + return _sign(key, 'request') + + +def _canonical_uri(key): + return '/' + quote(key.lstrip('/'), safe='/~') + + +def _scope(date, region): + return f'{date}/{region}/{SERVICE}/request' + + +def endpoint(region): + return f'tos-{region}.volces.com' + + +def object_url(bucket, region, key): + return f'https://{bucket}.{endpoint(region)}/{quote(key.lstrip("/"), safe="/~")}' + + +def presign(bucket, region, key, access_key, secret_key, *, expires=3600, now=None, + method='GET'): + moment = (now or datetime.now(timezone.utc)).replace(microsecond=0) + stamp = moment.strftime('%Y%m%dT%H%M%SZ') + date = stamp[:8] + host = f'{bucket}.{endpoint(region)}' + query = { + 'X-Tos-Algorithm': ALGORITHM, + 'X-Tos-Credential': f'{access_key}/{_scope(date, region)}', + 'X-Tos-Date': stamp, + 'X-Tos-Expires': str(int(expires)), + 'X-Tos-SignedHeaders': 'host', + } + canonical_query = '&'.join(f'{quote(k, safe="-_.~")}={quote(v, safe="-_.~")}' + for k, v in sorted(query.items())) + canonical_request = '\n'.join([method, _canonical_uri(key), canonical_query, + f'host:{host}\n', 'host', UNSIGNED]) + scope = _scope(date, region) + string_to_sign = '\n'.join([ALGORITHM, stamp, scope, + hashlib.sha256(canonical_request.encode()).hexdigest()]) + signature = hmac.new(_signing_key(secret_key, date, region), string_to_sign.encode(), + hashlib.sha256).hexdigest() + return f'https://{host}{_canonical_uri(key)}?{canonical_query}&X-Tos-Signature={signature}' + + +def authorization(bucket, region, key, access_key, secret_key, payload_hash, *, + now=None, method='PUT'): + moment = (now or datetime.now(timezone.utc)).replace(microsecond=0) + stamp = moment.strftime('%Y%m%dT%H%M%SZ') + date = stamp[:8] + host = f'{bucket}.{endpoint(region)}' + signed = 'host;x-tos-content-sha256;x-tos-date' + canonical_headers = (f'host:{host}\n' + f'x-tos-content-sha256:{payload_hash}\n' + f'x-tos-date:{stamp}\n') + canonical_request = '\n'.join([method, _canonical_uri(key), '', canonical_headers, + signed, payload_hash]) + scope = _scope(date, region) + string_to_sign = '\n'.join([ALGORITHM, stamp, scope, + hashlib.sha256(canonical_request.encode()).hexdigest()]) + signature = hmac.new(_signing_key(secret_key, date, region), string_to_sign.encode(), + hashlib.sha256).hexdigest() + headers = { + 'x-tos-content-sha256': payload_hash, + 'x-tos-date': stamp, + 'Authorization': (f'{ALGORITHM} Credential={access_key}/{scope}, ' + f'SignedHeaders={signed}, Signature={signature}'), + } + return headers + + +def put(session_settings, bucket, region, key, path, access_key, secret_key, *, + content_type='application/octet-stream', transport=None, now=None): + with open(path, 'rb') as handle: + payload = handle.read() + payload_hash = hashlib.sha256(payload).hexdigest() + headers = authorization(bucket, region, key, access_key, secret_key, payload_hash, + now=now) + headers['Content-Type'] = content_type + url = object_url(bucket, region, key) + try: + with httpx.Client(transport=transport, + trust_env=trust_environment(url, config=session_settings), + timeout=httpx.Timeout(300, connect=15)) as client: + response = client.put(url, content=payload, headers=headers) + except httpx.TimeoutException as exc: + raise TransferError('storage_timeout', str(exc)) from exc + except httpx.HTTPError as exc: + raise TransferError('storage_unreachable', str(exc)) from exc + if response.status_code >= 400: + raise TransferError('storage_rejected', response.text[:400]) + return len(payload) diff --git a/tests/test_tos_transfer.py b/tests/test_tos_transfer.py new file mode 100644 index 000000000..71ecff539 --- /dev/null +++ b/tests/test_tos_transfer.py @@ -0,0 +1,100 @@ +import hashlib +from datetime import datetime, timezone + +import httpx +import pytest + +from opendirector.integrations import tos_transfer as transfer + +MOMENT = datetime(2026, 12, 4, 1, 2, 3, tzinfo=timezone.utc) +CREDS = ('AKLTtest', 'secret-key') +BUCKET = 'opendirector' +REGION = 'cn-beijing' + + +def test_presigned_url_is_reproducible_for_a_fixed_moment(): + first = transfer.presign(BUCKET, REGION, 'od/clip.mp4', *CREDS, now=MOMENT) + second = transfer.presign(BUCKET, REGION, 'od/clip.mp4', *CREDS, now=MOMENT) + assert first == second + assert first.startswith('https://opendirector.tos-cn-beijing.volces.com/od/clip.mp4?') + assert 'X-Tos-Algorithm=TOS4-HMAC-SHA256' in first + assert 'X-Tos-Date=20261204T010203Z' in first + assert 'X-Tos-Expires=3600' in first + assert 'X-Tos-SignedHeaders=host' in first + assert 'X-Tos-Credential=AKLTtest%2F20261204%2Fcn-beijing%2Ftos%2Frequest' in first + + +def test_presigned_url_covers_the_object_key_the_expiry_and_the_secret(): + base = transfer.presign(BUCKET, REGION, 'od/a.mp4', *CREDS, now=MOMENT) + other_key = transfer.presign(BUCKET, REGION, 'od/b.mp4', *CREDS, now=MOMENT) + other_expiry = transfer.presign(BUCKET, REGION, 'od/a.mp4', *CREDS, expires=60, now=MOMENT) + other_secret = transfer.presign(BUCKET, REGION, 'od/a.mp4', 'AKLTtest', 'other', now=MOMENT) + signatures = {url.rsplit('X-Tos-Signature=', 1)[1] for url in + (base, other_key, other_expiry, other_secret)} + assert len(signatures) == 4 + + +def test_object_url_encodes_each_path_segment(): + assert transfer.object_url(BUCKET, REGION, 'od/clip 1.mp4') == ( + 'https://opendirector.tos-cn-beijing.volces.com/od/clip%201.mp4') + + +def test_put_signs_the_payload_and_reports_the_stored_bytes(tmp_path): + media = tmp_path / 'clip.mp4' + media.write_bytes(b'video-bytes') + seen = {} + + def handler(request): + seen['method'] = request.method + seen['headers'] = dict(request.headers) + seen['body'] = request.content + return httpx.Response(200, text='') + + stored = transfer.put(None, BUCKET, REGION, 'od/clip.mp4', str(media), *CREDS, + content_type='video/mp4', + transport=httpx.MockTransport(handler), now=MOMENT) + assert stored == 11 + assert seen['method'] == 'PUT' + assert seen['body'] == b'video-bytes' + assert seen['headers']['x-tos-content-sha256'] == hashlib.sha256(b'video-bytes').hexdigest() + assert seen['headers']['x-tos-date'] == '20261204T010203Z' + assert seen['headers']['content-type'] == 'video/mp4' + assert seen['headers']['authorization'].startswith('TOS4-HMAC-SHA256 Credential=AKLTtest/') + assert 'SignedHeaders=host;x-tos-content-sha256;x-tos-date' in seen['headers']['authorization'] + + +def test_put_rejects_a_refused_upload(tmp_path): + media = tmp_path / 'clip.mp4' + media.write_bytes(b'x') + transport = httpx.MockTransport(lambda request: httpx.Response(403, text='AccessDenied')) + with pytest.raises(transfer.TransferError) as error: + transfer.put(None, BUCKET, REGION, 'od/clip.mp4', str(media), *CREDS, + transport=transport, now=MOMENT) + assert error.value.code == 'storage_rejected' + assert 'AccessDenied' in str(error.value) + + +def test_put_reports_a_timeout_with_its_own_code(tmp_path): + media = tmp_path / 'clip.mp4' + media.write_bytes(b'x') + + def handler(request): + raise httpx.ReadTimeout('slow', request=request) + + with pytest.raises(transfer.TransferError) as error: + transfer.put(None, BUCKET, REGION, 'od/clip.mp4', str(media), *CREDS, + transport=httpx.MockTransport(handler), now=MOMENT) + assert error.value.code == 'storage_timeout' + + +def test_put_reports_an_unreachable_endpoint_with_its_own_code(tmp_path): + media = tmp_path / 'clip.mp4' + media.write_bytes(b'x') + + def handler(request): + raise httpx.ConnectError('dns', request=request) + + with pytest.raises(transfer.TransferError) as error: + transfer.put(None, BUCKET, REGION, 'od/clip.mp4', str(media), *CREDS, + transport=httpx.MockTransport(handler), now=MOMENT) + assert error.value.code == 'storage_unreachable' From b4586aaf2e5950482b32efb990a7b69b8de1e9d3 Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Fri, 4 Dec 2026 08:10:08 +0800 Subject: [PATCH 03/58] [feat] audio: dub a referenced video through the same Seed Audio model A dubbing request carries a `dubbing_video` and a language pair instead of a prompt, and comes back with three artifacts: the dubbed video, the extracted speech track and an SRT. The service refuses text in that scene, requires `dubbing_config`, and only accepts a video between 4 s and 6 min. The video is uploaded to the configured bucket and sent as a presigned URL, so a project video never has to be published. A missing storage configuration fails before submission with `seed_audio_storage` rather than after a wasted call. Verified against the live service: a 6 s clip with a speech track, uploaded to the bucket and presigned, returned `video_url`, one `audios` entry and one `subtitles` entry with `usage.duration_ms` 6016. Refs #650 --- .../application/creation_generation.py | 8 +- .../domain/creation/generation.py | 20 ++ .../src/opendirector/domain/input_rules.py | 5 +- .../src/opendirector/domain/rule_facts.py | 1 + .../integrations/reference_inputs.py | 17 +- .../opendirector/integrations/seed_audio.py | 35 ++++ .../opendirector/integrations/volcengine.py | 37 ++++ src/contracts/creation.schema.json | 180 ++++++++++++++++++ src/contracts/generated.ts | 8 + tests/test_seed_audio.py | 75 +++++++- 10 files changed, 377 insertions(+), 9 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 640768c15..13db48a12 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -222,6 +222,10 @@ def _parameters(self, spec, config, node, records): params[key] = intent[name] if intent.get('sampleRate'): params['sample_rate'] = intent['sampleRate'] + if intent.get('targetLanguage'): + params['target_language'] = intent['targetLanguage'] + if intent.get('sourceLanguage'): + params['source_language'] = intent['sourceLanguage'] elif spec.kind == 'audio' and intent.get('voice'): params['voice' if config['protocol'] == 'openai' else 'speaker'] = intent['voice'] if spec.kind == 'video': @@ -309,7 +313,9 @@ def _execution(kind, parameters, config): return dict(kind=kind, taskType=parameters.get('task', 'text2audio'), format=parameters.get('output_format', 'mp3'), sampleRate=parameters.get('sample_rate'), speechRate=parameters.get('speech_rate'), loudnessRate=parameters.get('loudness_rate'), - pitchRate=parameters.get('pitch_rate')) + pitchRate=parameters.get('pitch_rate'), + targetLanguage=parameters.get('target_language'), + sourceLanguage=parameters.get('source_language')) if kind == 'audio': if input_rules(config)['profile'] in {'moss-speech', 'minimax-speech'}: return dict(kind=kind, voice=parameters['voice'], format='mp3') diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 737773774..8e3488ff9 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -108,6 +108,22 @@ class AudioParameters(Contract): default='mp3', exclude_if=lambda value: value == 'mp3', description='Requested audio container format.') sampleRate: Literal[8000, 16000, 24000, 32000, 44100, 48000] | None = Field( default=None, exclude_if=lambda value: value is None, description='Requested audio samples per second.') + targetLanguage: Literal['zh', 'en', 'ja', 'ko', 'es', 'fr', 'de', 'it', 'pt', 'ru', + 'ar', 'th', 'vi', 'id', 'ms', 'tr', 'hi'] | None = Field( + default=None, exclude_if=lambda value: value is None, + description='Dubbing: language of the replacement speech track.') + sourceLanguage: Literal['zh', 'en', 'ja', 'ko', 'es', 'fr', 'de', 'it', 'pt', 'ru', + 'ar', 'th', 'vi', 'id', 'ms', 'tr', 'hi'] | None = Field( + default=None, exclude_if=lambda value: value is None, + description='Dubbing: language of the original speech track, detected when unset.') + targetLanguage: Literal['zh', 'en', 'ja', 'ko', 'es', 'fr', 'de', 'it', 'pt', 'ru', + 'ar', 'th', 'vi', 'id', 'ms', 'tr', 'hi'] | None = Field( + default=None, exclude_if=lambda value: value is None, + description='Dubbing: language of the replacement speech track.') + sourceLanguage: Literal['zh', 'en', 'ja', 'ko', 'es', 'fr', 'de', 'it', 'pt', 'ru', + 'ar', 'th', 'vi', 'id', 'ms', 'tr', 'hi'] | None = Field( + default=None, exclude_if=lambda value: value is None, + description='Dubbing: language of the original speech track, detected when unset.') @model_validator(mode='after') def voice_identity(self): @@ -295,6 +311,10 @@ class AudioExecution(Contract): description='Loudness offset fixed when the job was accepted.') pitchRate: int | None = Field(default=None, strict=True, exclude_if=lambda value: value is None, description='Pitch offset fixed when the job was accepted.') + targetLanguage: str | None = Field(default=None, exclude_if=lambda value: value is None, + description='Dubbing: language of the replacement track fixed when the job was accepted.') + sourceLanguage: str | None = Field(default=None, exclude_if=lambda value: value is None, + description='Dubbing: language of the original track fixed when the job was accepted.') creationType: Literal['audio', 'music'] = Field(default='audio', exclude_if=lambda value: value == 'audio', description='Speech or music creation mode.') # Legacy, see AudioParameters.instrumental. instrumental: bool = Field(default=False, exclude_if=lambda value: value is False, description='Legacy explicit instrumental choice retained for stored records.') diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index b319e67c8..488bfd030 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -179,8 +179,9 @@ def _adapter_rules(config): imageBytes=25 * 1024 * 1024, requestBytes=50 * 1024 * 1024, imageQualities=['auto', 'low', 'medium', 'high']) if kind == 'audio' and config.get('protocol') == 'volcengine' and str(config.get('modelId') or '').startswith(SEED_AUDIO_MODEL_PREFIX): - rules.update(profile='seed-audio', allowedKinds=['image', 'audio'], maxImages=1, maxAudios=6, - referencesAllowed=True, maxPromptCharacters=10000, audioTasks=['text2audio'], + rules.update(profile='seed-audio', allowedKinds=['image', 'audio', 'video'], maxImages=1, maxAudios=6, + maxVideos=1, referencesAllowed=True, maxPromptCharacters=10000, + audioTasks=['text2audio', 'dubbing'], outputFormats=['mp3', 'wav'], sampleRates=[8000, 16000, 24000, 32000, 44100, 48000]) return rules if kind == 'audio': diff --git a/packages/core/src/opendirector/domain/rule_facts.py b/packages/core/src/opendirector/domain/rule_facts.py index 0957b52ba..1fd86792c 100644 --- a/packages/core/src/opendirector/domain/rule_facts.py +++ b/packages/core/src/opendirector/domain/rule_facts.py @@ -14,6 +14,7 @@ SEED_AUDIO_REFERENCE_BYTES = 15 * 1024 * 1024 SEED_AUDIO_REFERENCE_MS = (2000, 30000) SEED_AUDIO_REFERENCE_TOTAL_MS = 180000 +SEED_AUDIO_DUBBING_MS = (4000, 360000) # Storage/structure guard. Provider budgets are checked separately. MAX_REFERENCES = 64 diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 8bc621b89..4725d5d91 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -5,7 +5,8 @@ from opendirector.domain.input_rules import MAX_REFERENCES, input_rules from opendirector.domain.rule_facts import ( - CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, SEED_AUDIO_REFERENCE_BYTES, SEED_AUDIO_REFERENCE_MS, SEED_AUDIO_REFERENCE_TOTAL_MS, TEXT_REFERENCE_BYTES, keyframe_frame, + CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, SEED_AUDIO_DUBBING_MS, SEED_AUDIO_REFERENCE_BYTES, SEED_AUDIO_REFERENCE_MS, + SEED_AUDIO_REFERENCE_TOTAL_MS, TEXT_REFERENCE_BYTES, keyframe_frame, ) from opendirector.domain.projects import ProjectError from opendirector.domain.minimax_image import validate_minimax_image_reference @@ -83,8 +84,9 @@ def reference_content(store, owner, message, *, manifest=None, overrides=None): def seed_audio_references(store, task, rules, result, overrides): - """Seed Audio takes one image or several voice samples, never both.""" + """Seed Audio takes one image, one video for dubbing, or voice samples, never a mix.""" total_ms = 0 + dubbing = (task.get('parameters') or {}).get('taskType') == 'dubbing' for data, meta, source_kind in references(store, task['projectId'], task['referenceIds'], overrides): entry = {'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': source_kind, 'transmission': 'content'} if source_kind == 'image': @@ -108,8 +110,19 @@ def seed_audio_references(store, task, rules, result, overrides): raise ProjectError(f'参考音频最多 {rules["maxAudios"]} 段、合计不超过 {SEED_AUDIO_REFERENCE_TOTAL_MS // 1000} 秒。', 422, code='audio_reference_count') result['audios'].append(data_uri(data, 'audio/wav' if meta['type'] == 'audio/x-wav' else meta['type'])) result['manifest'].append({**entry, 'role': 'reference_audio'}) + elif source_kind == 'video' and dubbing: + duration = meta.get('durationMs') + low, high = SEED_AUDIO_DUBBING_MS + if meta.get('type') not in {'video/mp4'} or duration is None or not low <= duration <= high: + raise ProjectError('翻配视频需为 MP4,时长 4 秒至 6 分钟。', 422, code='audio_reference_video') + if result['videos']: + raise ProjectError('翻配一次只能引用一段视频。', 422, code='audio_reference_count') + result['videos'].append(data) + result['manifest'].append({**entry, 'role': 'dubbing_video'}) else: raise ProjectError(f'“{meta["name"]}”:Seed Audio 1.5 暂不接受视频参考。', 422, code='audio_reference_video') + if result['videos'] and (result['images'] or result['audios']): + raise ProjectError('翻配视频不能与图片或音频参考同时使用。', 422, code='audio_reference_mix') if result['images'] and result['audios']: raise ProjectError('Seed Audio 1.5 的图片参考与音频参考不能同时使用。', 422, code='audio_reference_mix') return result diff --git a/packages/core/src/opendirector/integrations/seed_audio.py b/packages/core/src/opendirector/integrations/seed_audio.py index cdd6d95b8..070cfe5df 100644 --- a/packages/core/src/opendirector/integrations/seed_audio.py +++ b/packages/core/src/opendirector/integrations/seed_audio.py @@ -21,6 +21,41 @@ def request_body(config, prompt, parameters, images=(), audios=()): return body +def dubbing_body(config, video_url, parameters): + """Dubbing replaces the audio track, so the request carries no text.""" + config_body = {'target_language': parameters['target_language']} + if parameters.get('source_language'): + config_body['source_language'] = parameters['source_language'] + if parameters.get('subtitle_url'): + config_body['custom_subtitle'] = {'url': parameters['subtitle_url']} + body = {'model': config['modelId'], + 'content': [{'type': 'video_url', 'role': 'dubbing_video', + 'video_url': {'url': video_url}}], + 'dubbing_config': config_body, + 'include': ['video_url', 'subtitles.srt']} + return body + + +def dubbing_artifacts(value): + """The dubbed video, the extracted track and the subtitles, in that order.""" + content = value.get('content') or {} + video = content.get('video_url') + if not isinstance(video, str) or not video: + raise ValueError('Seed Audio returned no dubbed video') + artifacts = [('dubbed_video', video)] + for audio in content.get('audios') or []: + url = audio.get('url') if isinstance(audio, dict) else None + if isinstance(url, str) and url: + artifacts.append(('audio_track', url)) + break + for subtitle in content.get('subtitles') or []: + url = subtitle.get('url') if isinstance(subtitle, dict) else None + if isinstance(url, str) and url: + artifacts.append(('subtitle', url)) + break + return tuple(artifacts) + + def artifact_urls(value): """Artifact URLs in response order; the first one is the primary result.""" audios = value['content']['audios'] diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index 434cb29f9..f3adcc7cc 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -3,6 +3,8 @@ import asyncio import base64 import json +import os +import tempfile from urllib.parse import quote, urlsplit from uuid import uuid4 @@ -17,7 +19,9 @@ from opendirector.integrations.reference_inputs import generation_references, request_size from opendirector.integrations.generation_errors import checked, protocol_failure, provider_failure, transport_failure from opendirector.integrations.seed_audio import (artifact_urls as seed_audio_artifacts, is_seed_audio, + dubbing_artifacts as seed_audio_dubbing_artifacts, dubbing_body as seed_audio_dubbing_body, request_body as seed_audio_body) +from opendirector.integrations import tos_transfer from opendirector.media.probe import require_ffprobe @@ -205,6 +209,39 @@ async def query(): if value.get("status") not in {"queued", "running", "submitted"}: raise protocol_failure(stage) await asyncio.sleep(self.poll_interval) + if kind == "audio" and is_seed_audio(config["modelId"]) and task["parameters"].get("taskType") == "dubbing": + storage = config.get("storage") or {} + if not prepared["videos"]: + raise ProjectError("翻配需要引用一段视频。", 422, code="audio_reference_video") + if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): + raise ProjectError("翻配需要先配置对象存储,方舟只能拉取可访问的地址。", 422, + code="seed_audio_storage") + key = f"od/{task['id']}/{uuid4()}.mp4" + media = prepared["videos"][0] + path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.mp4") + with open(path, "wb") as handle: + handle.write(media) + try: + await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], + key, path, storage["accessKey"], storage["secretKey"], + content_type="video/mp4") + except tos_transfer.TransferError as error: + raise ProjectError("视频上传失败,请检查对象存储配置后重试。", 502, + code=f"seed_audio_{error.code}") from error + finally: + os.unlink(path) + source = tos_transfer.presign(storage["bucket"], storage["region"], key, + storage["accessKey"], storage["secretKey"], expires=3600) + payload = seed_audio_dubbing_body(config, source, task["parameters"]) + stage = 'submit' + async with client.stream("POST", endpoint(config["url"], "/contents/generations"), + headers=headers, json=payload) as response: + value = json.loads(await bounded(response, stage=stage, secrets=secrets)) + stage = 'download' + artifacts = seed_audio_dubbing_artifacts(value) + if result_ready: + await result_ready('mp4', artifacts[0][1]) + return "mp4", await self._download(client, artifacts[0][1], secrets=secrets) if kind == "audio" and is_seed_audio(config["modelId"]): payload = seed_audio_body(config, prompt, task["parameters"], prepared['images'], prepared['audios']) diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 04a8f7833..a24c53a6c 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -1327,6 +1327,32 @@ "description": "Pitch offset fixed when the job was accepted.", "title": "Pitchrate" }, + "targetLanguage": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: language of the replacement track fixed when the job was accepted.", + "title": "Targetlanguage" + }, + "sourceLanguage": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: language of the original track fixed when the job was accepted.", + "title": "Sourcelanguage" + }, "creationType": { "default": "audio", "description": "Speech or music creation mode.", @@ -1678,6 +1704,70 @@ "default": null, "description": "Requested audio samples per second.", "title": "Samplerate" + }, + "targetLanguage": { + "anyOf": [ + { + "enum": [ + "zh", + "en", + "ja", + "ko", + "es", + "fr", + "de", + "it", + "pt", + "ru", + "ar", + "th", + "vi", + "id", + "ms", + "tr", + "hi" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: language of the replacement speech track.", + "title": "Targetlanguage" + }, + "sourceLanguage": { + "anyOf": [ + { + "enum": [ + "zh", + "en", + "ja", + "ko", + "es", + "fr", + "de", + "it", + "pt", + "ru", + "ar", + "th", + "vi", + "id", + "ms", + "tr", + "hi" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: language of the original speech track, detected when unset.", + "title": "Sourcelanguage" } }, "title": "AudioParameters", @@ -21400,6 +21490,32 @@ "description": "Pitch offset fixed when the job was accepted.", "title": "Pitchrate" }, + "targetLanguage": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: language of the replacement track fixed when the job was accepted.", + "title": "Targetlanguage" + }, + "sourceLanguage": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: language of the original track fixed when the job was accepted.", + "title": "Sourcelanguage" + }, "creationType": { "default": "audio", "description": "Speech or music creation mode.", @@ -21761,6 +21877,70 @@ "default": null, "description": "Requested audio samples per second.", "title": "Samplerate" + }, + "targetLanguage": { + "anyOf": [ + { + "enum": [ + "zh", + "en", + "ja", + "ko", + "es", + "fr", + "de", + "it", + "pt", + "ru", + "ar", + "th", + "vi", + "id", + "ms", + "tr", + "hi" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: language of the replacement speech track.", + "title": "Targetlanguage" + }, + "sourceLanguage": { + "anyOf": [ + { + "enum": [ + "zh", + "en", + "ja", + "ko", + "es", + "fr", + "de", + "it", + "pt", + "ru", + "ar", + "th", + "vi", + "id", + "ms", + "tr", + "hi" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: language of the original speech track, detected when unset.", + "title": "Sourcelanguage" } }, "required": [ diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 89e0001af..f6a5c6f96 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -135,6 +135,8 @@ export interface AudioExecutionInput extends ContractInput { readonly speechRate?: number | null; readonly loudnessRate?: number | null; readonly pitchRate?: number | null; + readonly targetLanguage?: string | null; + readonly sourceLanguage?: string | null; readonly creationType?: "audio" | "music"; readonly instrumental?: boolean; readonly maxDurationSeconds?: number | null; @@ -163,6 +165,8 @@ export interface AudioParametersInput extends ContractInput { readonly pitchRate?: number; readonly outputFormat?: "mp3" | "wav"; readonly sampleRate?: 8000 | 16000 | 24000 | 32000 | 44100 | 48000 | null; + readonly targetLanguage?: "zh" | "en" | "ja" | "ko" | "es" | "fr" | "de" | "it" | "pt" | "ru" | "ar" | "th" | "vi" | "id" | "ms" | "tr" | "hi" | null; + readonly sourceLanguage?: "zh" | "en" | "ja" | "ko" | "es" | "fr" | "de" | "it" | "pt" | "ru" | "ar" | "th" | "vi" | "id" | "ms" | "tr" | "hi" | null; } export interface AvailabilityCatalogInput extends ContractInput { @@ -2186,6 +2190,8 @@ export interface AudioExecution extends Contract { readonly speechRate?: number | null; readonly loudnessRate?: number | null; readonly pitchRate?: number | null; + readonly targetLanguage?: string | null; + readonly sourceLanguage?: string | null; readonly creationType?: "audio" | "music"; readonly instrumental?: boolean; readonly maxDurationSeconds?: number | null; @@ -2214,6 +2220,8 @@ export interface AudioParameters extends Contract { readonly pitchRate?: number; readonly outputFormat?: "mp3" | "wav"; readonly sampleRate?: 8000 | 16000 | 24000 | 32000 | 44100 | 48000 | null; + readonly targetLanguage?: "zh" | "en" | "ja" | "ko" | "es" | "fr" | "de" | "it" | "pt" | "ru" | "ar" | "th" | "vi" | "id" | "ms" | "tr" | "hi" | null; + readonly sourceLanguage?: "zh" | "en" | "ja" | "ko" | "es" | "fr" | "de" | "it" | "pt" | "ru" | "ar" | "th" | "vi" | "id" | "ms" | "tr" | "hi" | null; } export interface AvailabilityCatalog extends Contract { diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index 50bf2a78b..85e244d2c 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -15,7 +15,8 @@ from opendirector.domain.creation.models import InputRules, ModelConfigPublic from opendirector.domain.input_rules import input_rules from opendirector.domain.projects import ProjectError -from opendirector.integrations.seed_audio import artifact_urls, request_body +from opendirector.integrations.seed_audio import (artifact_urls, dubbing_artifacts, dubbing_body, + request_body) from opendirector.integrations.volcengine import VolcengineGeneration from test_creation_contracts import entity, model as public_model from test_creation_canvas_service import project # noqa: F401 (pytest fixture) @@ -49,8 +50,8 @@ def seed_model(url=CONTENT_BASE): def test_adapter_publishes_only_the_verified_operation(): rules = InputRules.model_validate(input_rules(config())) assert rules.profile == 'seed-audio' - assert rules.audioTasks == ('text2audio',) - assert rules.allowedKinds == ('image', 'audio') and rules.maxImages == 1 and rules.maxAudios == 6 + assert rules.audioTasks == ('text2audio', 'dubbing') + assert rules.allowedKinds == ('image', 'audio', 'video') and rules.maxImages == 1 and rules.maxAudios == 6 assert rules.referencesAllowed is True assert rules.maxPromptCharacters == 10000 assert rules.outputFormats == ('mp3', 'wav') @@ -105,7 +106,7 @@ def test_unified_mode_is_accepted_only_for_the_unified_profile(): validate_generation(audio_spec(), seed_model()) for parameters, code in [({'mode': 'tts'}, 'audio_mode_required'), ({'creationType': 'music'}, 'audio_music_unsupported'), - ({'taskType': 'dubbing'}, 'audio_task_unsupported')]: + ({'taskType': 'separation'}, 'audio_task_unsupported')]: with pytest.raises(ProjectError) as caught: validate_generation(audio_spec(**parameters), seed_model()) assert caught.value.code == code @@ -238,3 +239,69 @@ def test_video_references_stay_unsupported(tmp_path): with pytest.raises(ProjectError) as failure: prepared(store, owner, [video]) assert failure.value.code == 'audio_reference_video' + + +def dubbing_task(owner, refs, **parameters): + return {'kind': 'audio', 'projectId': owner, 'prompt': '', 'referenceIds': [r['id'] for r in refs], + 'parameters': {'mode': 'unified', 'creationType': 'audio', 'taskType': 'dubbing', + 'target_language': 'zh', **parameters}} + + +def dubbing_ready(store, owner, refs, **parameters): + from opendirector.integrations.reference_inputs import generation_references + return generation_references(store, dubbing_task(owner, refs, **parameters), config()) + + +def dubbing_store(tmp_path, duration_ms): + store, owner, _, _, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=50)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': duration_ms} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + return store, owner, video + + +def test_dubbing_carries_the_video_and_language_without_text(tmp_path): + store, owner, video = dubbing_store(tmp_path, 6000) + ready = dubbing_ready(store, owner, [video]) + assert ready['videos'] == [b'private'] and ready['images'] == [] and ready['audios'] == [] + assert [entry['role'] for entry in ready['manifest']] == ['dubbing_video'] + body = dubbing_body(config(), 'https://storage.example/od/clip.mp4', + {'target_language': 'zh', 'source_language': 'en'}) + assert body['content'] == [{'type': 'video_url', 'role': 'dubbing_video', + 'video_url': {'url': 'https://storage.example/od/clip.mp4'}}] + assert body['dubbing_config'] == {'target_language': 'zh', 'source_language': 'en'} + assert body['include'] == ['video_url', 'subtitles.srt'] + assert 'text' not in body + + +def test_dubbing_artifacts_keep_the_video_track_and_subtitle_order(): + artifacts = dubbing_artifacts({'content': {'video_url': 'https://a/dubbed.mp4', + 'audios': [{'url': 'https://a/track.wav'}], + 'subtitles': [{'format': 'srt', 'url': 'https://a/line.srt'}]}}) + assert artifacts == (('dubbed_video', 'https://a/dubbed.mp4'), + ('audio_track', 'https://a/track.wav'), + ('subtitle', 'https://a/line.srt')) + + +def test_dubbing_requires_a_dubbed_video_in_the_response(): + with pytest.raises(ValueError, match='dubbed video'): + dubbing_artifacts({'content': {'audios': [{'url': 'https://a/track.wav'}]}}) + + +def test_dubbing_rejects_a_video_outside_the_accepted_duration(tmp_path): + store, owner, video = dubbing_store(tmp_path, 3000) + with pytest.raises(ProjectError) as failure: + dubbing_ready(store, owner, [video]) + assert failure.value.code == 'audio_reference_video' + + +def test_dubbing_cannot_mix_a_video_with_voice_samples(tmp_path): + store, owner, video = dubbing_store(tmp_path, 6000) + voice = {'id': str(UUID(int=51)), 'name': '样音.wav', 'type': 'audio/wav', 'kind': 'audio', + 'fingerprint': 'fixture', 'durationMs': 3000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', voice) if asset_id == voice['id'] else original(project_id, asset_id) + with pytest.raises(ProjectError) as failure: + dubbing_ready(store, owner, [video, voice]) + assert failure.value.code == 'audio_reference_mix' From 7833997b16c21f0093df2a236da72419266ea59c Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:11:30 +0800 Subject: [PATCH 04/58] [feat] audio: dub from a subtitle file and validate the dubbing language pair A dubbing request without a subtitle makes the service listen to the video. With one, the supplied lines win, which is what a translated script needs. The SRT is an asset of the project, uploaded through the same presigned channel as the video, so `custom_subtitle` never carries a URL the service cannot read. Validation now refuses a dubbing request without a target language, a language pair outside dubbing, a subtitle outside dubbing, and a subtitle that is not a timed SRT within 2 MB. Refs #650 --- apps/api/src/opendirector_api/localization.py | 2 + .../application/creation_generation.py | 5 +- .../opendirector/domain/creation/commands.py | 2 +- .../domain/creation/generation.py | 16 +++++ .../src/opendirector/domain/rule_facts.py | 1 + .../integrations/reference_inputs.py | 16 ++++- .../opendirector/integrations/seed_audio.py | 6 +- .../opendirector/integrations/volcengine.py | 19 +++++- src/contracts/creation.schema.json | 68 +++++++++++++++++++ src/contracts/generated.ts | 8 ++- tests/test_seed_audio.py | 51 ++++++++++++++ 11 files changed, 184 insertions(+), 10 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 4c101187b..f8df9321d 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -66,6 +66,8 @@ 'audio_reference_count': 'Seed Audio takes at most one image or six voice references, up to 180 seconds in total.', 'audio_reference_mix': 'Seed Audio cannot combine an image reference with voice references.', 'audio_reference_video': 'This Seed Audio adapter does not accept video references yet.', + 'audio_subtitle_scope': 'A subtitle file is used only when dubbing a referenced video.', + 'audio_subtitle_asset': 'The subtitle must be an SRT file within the size limit.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', 'bigmodel_video_output': 'Choose a supported CogVideoX-3 pixel size and a 5- or 10-second duration. The size determines the aspect ratio.', 'bigmodel_video_image': 'CogVideoX-3 frame images must be valid PNG or JPEG files, up to 5 MB each.', diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 13db48a12..534351c25 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -226,6 +226,8 @@ def _parameters(self, spec, config, node, records): params['target_language'] = intent['targetLanguage'] if intent.get('sourceLanguage'): params['source_language'] = intent['sourceLanguage'] + if intent.get('subtitleAssetId'): + params['subtitleAssetId'] = str(intent['subtitleAssetId']) elif spec.kind == 'audio' and intent.get('voice'): params['voice' if config['protocol'] == 'openai' else 'speaker'] = intent['voice'] if spec.kind == 'video': @@ -315,7 +317,8 @@ def _execution(kind, parameters, config): speechRate=parameters.get('speech_rate'), loudnessRate=parameters.get('loudness_rate'), pitchRate=parameters.get('pitch_rate'), targetLanguage=parameters.get('target_language'), - sourceLanguage=parameters.get('source_language')) + sourceLanguage=parameters.get('source_language'), + subtitleAssetId=parameters.get('subtitleAssetId')) if kind == 'audio': if input_rules(config)['profile'] in {'moss-speech', 'minimax-speech'}: return dict(kind=kind, voice=parameters['voice'], format='mp3') diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index d35657292..6ee989205 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -606,7 +606,7 @@ def command_fingerprint(command: Command) -> str: 'capability_unsupported', 'preview_expired', 'storage_unavailable', 'submission_unknown', 'provider_error', 'audio_music_unsupported', 'audio_mode_required', 'audio_task_unsupported', 'seed_audio_base_url', 'audio_reference_image', 'audio_reference_audio', 'audio_reference_count', 'audio_reference_mix', - 'audio_reference_video', + 'audio_reference_video', 'audio_subtitle_scope', 'audio_subtitle_asset', 'seed_audio_storage', 'seed_audio_storage_rejected', 'seed_audio_storage_timeout', 'seed_audio_storage_unreachable', 'moss_speech_text', 'moss_speech_voice', 'moss_speech_reference', 'moss_prompt_limit', 'moss_image_size', 'moss_image_reference', 'moss_layout_reference', 'bigmodel_image_size', 'bigmodel_image_reference', 'bigmodel_image_prompt', diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 8e3488ff9..e3efc5207 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -116,6 +116,9 @@ class AudioParameters(Contract): 'ar', 'th', 'vi', 'id', 'ms', 'tr', 'hi'] | None = Field( default=None, exclude_if=lambda value: value is None, description='Dubbing: language of the original speech track, detected when unset.') + subtitleAssetId: UUID | None = Field( + default=None, exclude_if=lambda value: value is None, + description='Dubbing: SRT asset that fixes the spoken lines instead of listening to the video.') targetLanguage: Literal['zh', 'en', 'ja', 'ko', 'es', 'fr', 'de', 'it', 'pt', 'ru', 'ar', 'th', 'vi', 'id', 'ms', 'tr', 'hi'] | None = Field( default=None, exclude_if=lambda value: value is None, @@ -125,6 +128,17 @@ class AudioParameters(Contract): default=None, exclude_if=lambda value: value is None, description='Dubbing: language of the original speech track, detected when unset.') + @model_validator(mode='after') + def dubbing_language(self): + if self.taskType == 'dubbing': + if self.targetLanguage is None: + raise ValueError('Dubbing needs a target language') + elif self.targetLanguage is not None or self.sourceLanguage is not None: + raise ValueError('Language selection applies to dubbing only') + if self.subtitleAssetId is not None and self.taskType != 'dubbing': + raise ValueError('A subtitle asset applies to dubbing only') + return self + @model_validator(mode='after') def voice_identity(self): if self.voiceSelection is not None: @@ -315,6 +329,8 @@ class AudioExecution(Contract): description='Dubbing: language of the replacement track fixed when the job was accepted.') sourceLanguage: str | None = Field(default=None, exclude_if=lambda value: value is None, description='Dubbing: language of the original track fixed when the job was accepted.') + subtitleAssetId: UUID | None = Field(default=None, exclude_if=lambda value: value is None, + description='Dubbing: subtitle asset that fixed the spoken lines when the job was accepted.') creationType: Literal['audio', 'music'] = Field(default='audio', exclude_if=lambda value: value == 'audio', description='Speech or music creation mode.') # Legacy, see AudioParameters.instrumental. instrumental: bool = Field(default=False, exclude_if=lambda value: value is False, description='Legacy explicit instrumental choice retained for stored records.') diff --git a/packages/core/src/opendirector/domain/rule_facts.py b/packages/core/src/opendirector/domain/rule_facts.py index 1fd86792c..77fc30cfb 100644 --- a/packages/core/src/opendirector/domain/rule_facts.py +++ b/packages/core/src/opendirector/domain/rule_facts.py @@ -15,6 +15,7 @@ SEED_AUDIO_REFERENCE_MS = (2000, 30000) SEED_AUDIO_REFERENCE_TOTAL_MS = 180000 SEED_AUDIO_DUBBING_MS = (4000, 360000) +SEED_AUDIO_SUBTITLE_BYTES = 2 * 1024 * 1024 # Storage/structure guard. Provider budgets are checked separately. MAX_REFERENCES = 64 diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 4725d5d91..5f114eb5b 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -5,7 +5,7 @@ from opendirector.domain.input_rules import MAX_REFERENCES, input_rules from opendirector.domain.rule_facts import ( - CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, SEED_AUDIO_DUBBING_MS, SEED_AUDIO_REFERENCE_BYTES, SEED_AUDIO_REFERENCE_MS, + CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, SEED_AUDIO_DUBBING_MS, SEED_AUDIO_REFERENCE_BYTES, SEED_AUDIO_SUBTITLE_BYTES, SEED_AUDIO_REFERENCE_MS, SEED_AUDIO_REFERENCE_TOTAL_MS, TEXT_REFERENCE_BYTES, keyframe_frame, ) from opendirector.domain.projects import ProjectError @@ -121,6 +121,18 @@ def seed_audio_references(store, task, rules, result, overrides): result['manifest'].append({**entry, 'role': 'dubbing_video'}) else: raise ProjectError(f'“{meta["name"]}”:Seed Audio 1.5 暂不接受视频参考。', 422, code='audio_reference_video') + subtitle_id = (task.get('parameters') or {}).get('subtitleAssetId') + if subtitle_id: + if not dubbing or not result['videos']: + raise ProjectError('字幕文件只在翻配视频时使用。', 422, code='audio_subtitle_scope') + data, meta = store.asset(task['projectId'], str(subtitle_id)) + text = data.decode('utf-8', 'replace') + if (meta.get('type') not in {'text/plain', 'application/x-subrip'} or len(data) > SEED_AUDIO_SUBTITLE_BYTES + or '-->' not in text): + raise ProjectError('字幕文件需为不超过 2 MB 的 SRT。', 422, code='audio_subtitle_asset') + result['subtitle'] = data + result['manifest'].append({'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': 'text', + 'transmission': 'content', 'role': 'custom_subtitle'}) if result['videos'] and (result['images'] or result['audios']): raise ProjectError('翻配视频不能与图片或音频参考同时使用。', 422, code='audio_reference_mix') if result['images'] and result['audios']: @@ -148,7 +160,7 @@ def generation_references(store, task, config, *, complete=True, overrides=None) rules = input_rules({**config, 'kind': 'agent' if kind == 'text' else kind}) mode = task.get('videoMode', 'first_frame') prompt = project_content(task['promptContent'], speech=kind == 'audio')[0] if task.get('promptContent') is not None else task['prompt'] - result = {'prompt': prompt, 'images': [], 'imageRoles': [], 'audios': [], 'videos': [], 'manifest': [], 'rules': rules, 'continueFrom': None, 'continueSize': None, 'control': None, 'guides': []} + result = {'prompt': prompt, 'images': [], 'imageRoles': [], 'audios': [], 'videos': [], 'manifest': [], 'subtitle': None, 'rules': rules, 'continueFrom': None, 'continueSize': None, 'control': None, 'guides': []} if kind == 'text': result['content'] = reference_content(store, task['projectId'], {'text': task['prompt'], 'content': task.get('promptContent'), 'assets': [{'id': asset_id} for asset_id in task['referenceIds']]}, manifest=result['manifest'], overrides=overrides) request_size(result['content'], rules['requestBytes']) diff --git a/packages/core/src/opendirector/integrations/seed_audio.py b/packages/core/src/opendirector/integrations/seed_audio.py index 070cfe5df..8398c5748 100644 --- a/packages/core/src/opendirector/integrations/seed_audio.py +++ b/packages/core/src/opendirector/integrations/seed_audio.py @@ -21,13 +21,13 @@ def request_body(config, prompt, parameters, images=(), audios=()): return body -def dubbing_body(config, video_url, parameters): +def dubbing_body(config, video_url, parameters, subtitle_url=None): """Dubbing replaces the audio track, so the request carries no text.""" config_body = {'target_language': parameters['target_language']} if parameters.get('source_language'): config_body['source_language'] = parameters['source_language'] - if parameters.get('subtitle_url'): - config_body['custom_subtitle'] = {'url': parameters['subtitle_url']} + if subtitle_url: + config_body['custom_subtitle'] = {'url': subtitle_url} body = {'model': config['modelId'], 'content': [{'type': 'video_url', 'role': 'dubbing_video', 'video_url': {'url': video_url}}], diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index f3adcc7cc..55791ac19 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -232,7 +232,24 @@ async def query(): os.unlink(path) source = tos_transfer.presign(storage["bucket"], storage["region"], key, storage["accessKey"], storage["secretKey"], expires=3600) - payload = seed_audio_dubbing_body(config, source, task["parameters"]) + subtitle_url = None + if prepared.get("subtitle"): + subtitle_key = f"od/{task['id']}/{uuid4()}.srt" + subtitle_path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.srt") + with open(subtitle_path, "wb") as handle: + handle.write(prepared["subtitle"]) + try: + await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], + subtitle_key, subtitle_path, storage["accessKey"], + storage["secretKey"], content_type="application/x-subrip") + except tos_transfer.TransferError as error: + raise ProjectError("字幕上传失败,请检查对象存储配置后重试。", 502, + code=f"seed_audio_{error.code}") from error + finally: + os.unlink(subtitle_path) + subtitle_url = tos_transfer.presign(storage["bucket"], storage["region"], subtitle_key, + storage["accessKey"], storage["secretKey"], expires=3600) + payload = seed_audio_dubbing_body(config, source, task["parameters"], subtitle_url) stage = 'submit' async with client.stream("POST", endpoint(config["url"], "/contents/generations"), headers=headers, json=payload) as response: diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index a24c53a6c..31c4dbdc1 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -1353,6 +1353,20 @@ "description": "Dubbing: language of the original track fixed when the job was accepted.", "title": "Sourcelanguage" }, + "subtitleAssetId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: subtitle asset that fixed the spoken lines when the job was accepted.", + "title": "Subtitleassetid" + }, "creationType": { "default": "audio", "description": "Speech or music creation mode.", @@ -1768,6 +1782,20 @@ "default": null, "description": "Dubbing: language of the original speech track, detected when unset.", "title": "Sourcelanguage" + }, + "subtitleAssetId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: SRT asset that fixes the spoken lines instead of listening to the video.", + "title": "Subtitleassetid" } }, "title": "AudioParameters", @@ -4755,6 +4783,12 @@ "audio_reference_count", "audio_reference_mix", "audio_reference_video", + "audio_subtitle_scope", + "audio_subtitle_asset", + "seed_audio_storage", + "seed_audio_storage_rejected", + "seed_audio_storage_timeout", + "seed_audio_storage_unreachable", "moss_speech_text", "moss_speech_voice", "moss_speech_reference", @@ -21516,6 +21550,20 @@ "description": "Dubbing: language of the original track fixed when the job was accepted.", "title": "Sourcelanguage" }, + "subtitleAssetId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: subtitle asset that fixed the spoken lines when the job was accepted.", + "title": "Subtitleassetid" + }, "creationType": { "default": "audio", "description": "Speech or music creation mode.", @@ -21941,6 +21989,20 @@ "default": null, "description": "Dubbing: language of the original speech track, detected when unset.", "title": "Sourcelanguage" + }, + "subtitleAssetId": { + "anyOf": [ + { + "format": "uuid", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Dubbing: SRT asset that fixes the spoken lines instead of listening to the video.", + "title": "Subtitleassetid" } }, "required": [ @@ -25004,6 +25066,12 @@ "audio_reference_count", "audio_reference_mix", "audio_reference_video", + "audio_subtitle_scope", + "audio_subtitle_asset", + "seed_audio_storage", + "seed_audio_storage_rejected", + "seed_audio_storage_timeout", + "seed_audio_storage_unreachable", "moss_speech_text", "moss_speech_voice", "moss_speech_reference", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index f6a5c6f96..02686afae 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -137,6 +137,7 @@ export interface AudioExecutionInput extends ContractInput { readonly pitchRate?: number | null; readonly targetLanguage?: string | null; readonly sourceLanguage?: string | null; + readonly subtitleAssetId?: string | null; readonly creationType?: "audio" | "music"; readonly instrumental?: boolean; readonly maxDurationSeconds?: number | null; @@ -167,6 +168,7 @@ export interface AudioParametersInput extends ContractInput { readonly sampleRate?: 8000 | 16000 | 24000 | 32000 | 44100 | 48000 | null; readonly targetLanguage?: "zh" | "en" | "ja" | "ko" | "es" | "fr" | "de" | "it" | "pt" | "ru" | "ar" | "th" | "vi" | "id" | "ms" | "tr" | "hi" | null; readonly sourceLanguage?: "zh" | "en" | "ja" | "ko" | "es" | "fr" | "de" | "it" | "pt" | "ru" | "ar" | "th" | "vi" | "id" | "ms" | "tr" | "hi" | null; + readonly subtitleAssetId?: string | null; } export interface AvailabilityCatalogInput extends ContractInput { @@ -511,7 +513,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -2192,6 +2194,7 @@ export interface AudioExecution extends Contract { readonly pitchRate?: number | null; readonly targetLanguage?: string | null; readonly sourceLanguage?: string | null; + readonly subtitleAssetId?: string | null; readonly creationType?: "audio" | "music"; readonly instrumental?: boolean; readonly maxDurationSeconds?: number | null; @@ -2222,6 +2225,7 @@ export interface AudioParameters extends Contract { readonly sampleRate?: 8000 | 16000 | 24000 | 32000 | 44100 | 48000 | null; readonly targetLanguage?: "zh" | "en" | "ja" | "ko" | "es" | "fr" | "de" | "it" | "pt" | "ru" | "ar" | "th" | "vi" | "id" | "ms" | "tr" | "hi" | null; readonly sourceLanguage?: "zh" | "en" | "ja" | "ko" | "es" | "fr" | "de" | "it" | "pt" | "ru" | "ar" | "th" | "vi" | "id" | "ms" | "tr" | "hi" | null; + readonly subtitleAssetId?: string | null; } export interface AvailabilityCatalog extends Contract { @@ -2566,7 +2570,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId: string | null; readonly field: string | null; diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index 85e244d2c..c84853dbc 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -305,3 +305,54 @@ def test_dubbing_cannot_mix_a_video_with_voice_samples(tmp_path): with pytest.raises(ProjectError) as failure: dubbing_ready(store, owner, [video, voice]) assert failure.value.code == 'audio_reference_mix' + + +def test_dubbing_carries_a_custom_subtitle_url(tmp_path): + store, owner, video = dubbing_store(tmp_path, 6000) + ready = dubbing_ready(store, owner, [video]) + body = dubbing_body(config(), 'https://storage.example/od/clip.mp4', + {'target_language': 'en'}, 'https://storage.example/od/lines.srt') + assert body['dubbing_config']['custom_subtitle'] == {'url': 'https://storage.example/od/lines.srt'} + assert ready['subtitle'] is None + + +def test_a_subtitle_asset_travels_with_the_dubbed_video(tmp_path): + store, owner, video = dubbing_store(tmp_path, 6000) + srt = {'id': str(UUID(int=60)), 'name': '台词.srt', 'type': 'text/plain', 'kind': 'text', + 'fingerprint': 'fixture'} + original = store.asset + body = b'1\n00:00:00,000 --> 00:00:02,000\n\n' + store.asset = lambda project_id, asset_id: (body, srt) if asset_id == srt['id'] else original(project_id, asset_id) + task = dubbing_task(owner, [video]) + task['parameters']['subtitleAssetId'] = srt['id'] + from opendirector.integrations.reference_inputs import generation_references + ready = generation_references(store, task, config()) + assert ready['subtitle'] == body + assert [entry['role'] for entry in ready['manifest']] == ['dubbing_video', 'custom_subtitle'] + + +def test_a_subtitle_outside_dubbing_is_refused(tmp_path): + store, owner, _, voice, _ = reference_store(tmp_path) + srt = {'id': str(UUID(int=61)), 'name': '台词.srt', 'type': 'text/plain', 'kind': 'text', + 'fingerprint': 'fixture'} + original = store.asset + store.asset = lambda project_id, asset_id: (b'1\n-->0\n', srt) if asset_id == srt['id'] else original(project_id, asset_id) + task = store_task(owner, [voice]) + task['parameters']['subtitleAssetId'] = srt['id'] + from opendirector.integrations.reference_inputs import generation_references + with pytest.raises(ProjectError) as failure: + generation_references(store, task, config()) + assert failure.value.code == 'audio_subtitle_scope' + + +def test_a_subtitle_that_is_not_srt_is_refused(tmp_path): + store, owner, video = dubbing_store(tmp_path, 6000) + bad = {'id': str(UUID(int=62)), 'name': '台词.txt', 'type': 'text/plain', 'kind': 'text', 'fingerprint': 'x'} + original = store.asset + store.asset = lambda project_id, asset_id: (b'no timings', bad) if asset_id == bad['id'] else original(project_id, asset_id) + task = dubbing_task(owner, [video]) + task['parameters']['subtitleAssetId'] = bad['id'] + from opendirector.integrations.reference_inputs import generation_references + with pytest.raises(ProjectError) as failure: + generation_references(store, task, config()) + assert failure.value.code == 'audio_subtitle_asset' From ba8dc53e38f6e30a065925796ded54c95a4f39bc Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Fri, 4 Dec 2026 10:33:32 +0800 Subject: [PATCH 05/58] [fix] audio: keep one language field per dubbing endpoint The dubbing parameters declared `targetLanguage` twice, so only the last declaration reached the generated contract and the adapter snapshot. Refs #650 --- .../core/src/opendirector/domain/creation/generation.py | 8 -------- 1 file changed, 8 deletions(-) diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index e3efc5207..091afee4f 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -119,14 +119,6 @@ class AudioParameters(Contract): subtitleAssetId: UUID | None = Field( default=None, exclude_if=lambda value: value is None, description='Dubbing: SRT asset that fixes the spoken lines instead of listening to the video.') - targetLanguage: Literal['zh', 'en', 'ja', 'ko', 'es', 'fr', 'de', 'it', 'pt', 'ru', - 'ar', 'th', 'vi', 'id', 'ms', 'tr', 'hi'] | None = Field( - default=None, exclude_if=lambda value: value is None, - description='Dubbing: language of the replacement speech track.') - sourceLanguage: Literal['zh', 'en', 'ja', 'ko', 'es', 'fr', 'de', 'it', 'pt', 'ru', - 'ar', 'th', 'vi', 'id', 'ms', 'tr', 'hi'] | None = Field( - default=None, exclude_if=lambda value: value is None, - description='Dubbing: language of the original speech track, detected when unset.') @model_validator(mode='after') def dubbing_language(self): From c61f713eb059f99ad2fd66b4147d0611675d1806 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 10:32:50 +0800 Subject: [PATCH 06/58] [feat] generation: keep every artifact a job produces ## summary One generation task can now deliver several files instead of silently keeping only the first: a dubbed video, separated audio tracks, and subtitle sidecars all land in the same project as real, inspectable assets. - `ResultVersion` carries `role`, `variant`, and `track`; `primary` stays the adopted output referenced by `Job.asset`. - Providers may return `GeneratedArtifact` items through an optional `generate_all()`; the single-file `generate()` default keeps existing adapters unchanged. - The adopted output and its siblings register in one commit under their own idempotent handles, so a failure never leaves an output without its siblings, and recovery replays the same commit without duplicates. - Artifact bytes are cached before the index (`artifacts.json`), and an index that cannot be validated is rejected instead of half-applied. - `result.select` rejects sidecars, and `job.status` reports every delivered artifact so users and the agent read the same projection. --- docs/architecture/unified-project.md | 4 + .../application/creation_assets.py | 31 ++- .../application/creation_canvas.py | 8 + .../application/creation_generation.py | 42 ++- .../application/generation_runtime.py | 30 ++- .../opendirector/domain/creation/commands.py | 4 +- .../domain/creation/generation.py | 6 + .../opendirector/domain/creation/project.py | 12 +- .../infrastructure/generation_results.py | 69 ++++- .../opendirector/integrations/providers.py | 26 ++ src/contracts/creation.schema.json | 85 +++++- src/contracts/generated.ts | 10 +- tests/fixtures/creation-project.json | 3 +- tests/test_result_artifacts.py | 247 ++++++++++++++++++ 14 files changed, 546 insertions(+), 31 deletions(-) create mode 100644 tests/test_result_artifacts.py diff --git a/docs/architecture/unified-project.md b/docs/architecture/unified-project.md index 411e0440c..f8b58b645 100644 --- a/docs/architecture/unified-project.md +++ b/docs/architecture/unified-project.md @@ -150,6 +150,10 @@ UI、Agent 和后台完成写入共享可恢复变更通道。通知提示对象 生成结果保留服务端返回的原始文件,不自动裁剪、丢帧、重编码或替换音轨。请求时长与帧数属于执行输入,输出媒体事实依据实际文件记录;模型对齐产生的差异如实保留。片段范围通过时间线显式编辑,转码和音轨调整产生独立派生素材,保留原始结果及来源关系。首次下载、失败恢复及各操作入口遵循同一规则。 +一次生成可以交付多个文件,例如配音后的视频、分离音轨和字幕。采用只有一个指针:`Job.asset` 与 `result.select` 只接受 `role="primary"` 的结果;其余文件属于同一任务的交付物,身份由 `(role, variant, track)` 确定,不使用供应商返回顺序编号。主结果与附加文件在同一个提交中登记,失败不会留下“主结果已在、兄弟文件丢失”的状态;中断后按恢复缓存重放同一提交,不重复登记。任务查询(`job.status` 与画布任务卡)同时返回交付文件清单,用户与 Agent 据此继续导入时间线或审片。 + +One generation can deliver several files, such as a dubbed video, separated audio tracks, and subtitles. Adoption stays a single pointer: `Job.asset` and `result.select` only accept the `role="primary"` result. The other files are deliverables of the same job, identified by `(role, variant, track)` rather than by vendor response order. The adopted output and its siblings are registered in one commit, so a failure never leaves "adopted output present, sibling lost", and recovery replays the same commit instead of duplicating it. Job queries (`job.status` and canvas job cards) return the delivered artifact list, so a user or the Agent can continue into the timeline or review. + 浏览器与后台的执行职责必须明确。Agent 可以修改时间线,不代表后台已经能够导出视频;只有存在可调用渲染服务并验证真实输出,才可声称支持关闭浏览器后的自主导出。浏览器合成也可以作为明确需要客户端参与的能力保留。 ### 动效编辑文档与后台渲染 / Motion documents and background rendering diff --git a/packages/core/src/opendirector/application/creation_assets.py b/packages/core/src/opendirector/application/creation_assets.py index 054cad5ce..255b9b374 100644 --- a/packages/core/src/opendirector/application/creation_assets.py +++ b/packages/core/src/opendirector/application/creation_assets.py @@ -1,5 +1,6 @@ """Shared C04 asset registration for uploads, text and trusted media outputs.""" from collections import OrderedDict +import contextlib from io import BytesIO import os import subprocess @@ -136,12 +137,15 @@ def _reference(cls, snapshot, reference): raise ContractError('reference_invalid', 'Asset reference differs from its content', asset.id) return asset - def register(self, command, *, session=None, source='ui', provenance=None, apply=None, upload_handle=None, trusted_upload=False): + def register(self, command, *, session=None, source='ui', provenance=None, apply=None, upload_handle=None, trusted_upload=False, staged=()): """Trusted services may supply provenance and atomically update jobs/editors. HTTP never accepts these extra arguments. trusted_upload selects a server-owned staged file while commit still validates the caller's editing session. Generated/edited outputs - must have real job/document evidence validated by ProjectSnapshot. + must have real job/document evidence validated by ProjectSnapshot. staged lists further + server-owned outputs, already staged under their own handles, that belong to the same + commit: one produced file must never be registered while its siblings are lost. Those + siblings are already present in the snapshot handed to apply. """ replay = self.projects.replay(command) if replay is not None: @@ -150,12 +154,27 @@ def register(self, command, *, session=None, source='ui', provenance=None, apply if command.type != 'asset.import' and not (command.type == 'artifact.publish' and upload_handle is not None): raise ProjectError('文件登记需要素材导入命令。') handle = payload.uploadHandle if command.type == 'asset.import' else upload_handle - with self.uploads.lock(command.projectId, handle): + with contextlib.ExitStack() as locks: + locks.enter_context(self.uploads.lock(command.projectId, handle)) + for extra_handle, _, _ in staged: + locks.enter_context(self.uploads.lock(command.projectId, extra_handle)) _, owner, record = self.uploads.ready(command.projectId, handle, None if trusted_upload else session) asset = Asset(id=gateway().upload_asset_id(command.projectId, handle), projectId=command.projectId, kind=record.kind, name=gateway().asset_name(payload.name), fingerprint=record.fingerprint, path=f'assets/{gateway().upload_asset_id(command.projectId, handle)}', metadata=record.metadata, provenance=provenance or AssetProvenance(source='upload')) + extra_assets, writes = [], [] + for extra_handle, extra_name, extra_kind in staged: + _, _, extra_record = self.uploads.ready(command.projectId, extra_handle, None if trusted_upload else session) + if extra_record.kind != extra_kind: + raise ContractError('invalid_input', 'Produced media kind differs from the declared artifact') + extra_id = gateway().upload_asset_id(command.projectId, extra_handle) + extra_assets.append(Asset(id=extra_id, projectId=command.projectId, kind=extra_record.kind, + name=gateway().asset_name(extra_name), fingerprint=extra_record.fingerprint, + path=f'assets/{extra_id}', metadata=extra_record.metadata, + provenance=provenance or AssetProvenance(source='upload'))) + writes.append(AssetFileWrite(assetId=extra_id, uploadHandle=extra_handle, + fingerprint=extra_record.fingerprint, size=extra_record.metadata.size)) def register(before): if payload.expectedKind is not None and payload.expectedKind != record.kind: raise ContractError('invalid_input', 'Uploaded media kind differs from the command') @@ -166,12 +185,14 @@ def register(before): return before data = before.model_dump() data['assets'] = [*before.assets, asset] - after = ProjectSnapshot.model_validate(data) if apply is None else apply(before, asset) + base = (before.model_copy(update={'assets': (*before.assets, *extra_assets)}) + if extra_assets else before) + after = ProjectSnapshot.model_validate(data) if apply is None else apply(base, asset) if not any(item == asset for item in after.assets): raise ContractError('invalid_input', 'Output registration must include its inspected asset', asset.id) return after write = AssetFileWrite(assetId=asset.id, uploadHandle=handle, fingerprint=asset.fingerprint, size=asset.metadata.size) - return self.projects.commit(command, register, session=session, source=source, files=(write,)) + return self.projects.commit(command, register, session=session, source=source, files=(write, *writes)) def write_text(self, command, *, session=None, source='ui', provenance=None): replay = self.projects.replay(command) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 25b4fd196..339149a28 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -774,6 +774,8 @@ def _mutate(self, data, kind, payload): result = self._get(data, 'result', payload.resultId) if result['specId'] != spec['id']: raise ContractError('invalid_input', '结果不属于该生成配置。', payload.resultId) + if result.get('role', 'primary') != 'primary': + raise ContractError('result_not_adoptable', '附加产物(音轨、字幕)不能替代主结果采用。', payload.resultId) stream, _ = self.assets.open_media(data['project']['id'], result['asset']['assetId']) stream.close() spec['currentResultId'] = result['id'] @@ -824,8 +826,11 @@ def job_states(self, project_id: UUID, object_ids: tuple[UUID, ...] = ()) -> dic else: selected = [job for job in snapshot.jobs if job.status not in self.TERMINAL_JOB_STATES] results_by_asset = {} + extras_by_job = {} for result in snapshot.results: results_by_asset.setdefault(result.asset.assetId, []).append(result) + if result.role != 'primary': + extras_by_job.setdefault(result.jobId, []).append(result) adopted_results = {spec.currentResultId for spec in snapshot.generationSpecs if spec.currentResultId} views = [] for job in selected: @@ -840,6 +845,9 @@ def job_states(self, project_id: UUID, object_ids: tuple[UUID, ...] = ()) -> dic and not item.binding.materialOverride) or (item.binding.role == 'material' and item.binding.objectRef.assetId == job.asset.assetId)] view['delivery'] = {'registered': True, 'asset': view['asset'], + 'artifacts': [{'id': str(result.id), 'role': result.role, 'variant': result.variant, + 'track': result.track, 'asset': result.asset.model_dump(mode='json')} + for result in extras_by_job.get(job.id, ())], 'adopted': any(result.id in adopted_results for result in results), 'canvasItems': [item.model_dump(mode='json', include={'id', 'revision', 'visible', 'position', 'width', 'height'}) for item in items], 'guidance': DELIVERY_GUIDANCE} diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 534351c25..b0ffad963 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -39,7 +39,7 @@ from opendirector.integrations.fasth3 import control_parameters, video_parameters from opendirector.integrations.vllm_omni import FPS, video_frame_parameters from opendirector.integrations.model_adapters import capabilities_of -from opendirector.integrations.providers import GenerationProviders +from opendirector.integrations.providers import GenerationProviders, artifact_kind from opendirector.media.filenames import with_extension _INPUTS = ContextVar('creation_generation_inputs', default=None) @@ -592,35 +592,56 @@ def _result_asset(self, task, directory): return None def _commit_output(self, task, pinned, suffix, data): + cache = gateway().results(pinned, task['id']) existing = self._result_asset(task, pinned) - if existing: + if existing and not cache.artifacts(): return existing job = self.get_job(task['projectId'], task['id']) handle = uuid5(job.id, 'output-upload') name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', task['title']).strip(' .')[:180] or job.execution.kind - self.assets.stage_output(job.projectId, handle, with_extension(name, suffix), - gateway().results(pinned, task['id']).directory / 'output', expected_kind=job.execution.kind) + if not existing: + self.assets.stage_output(job.projectId, handle, with_extension(name, suffix), + cache.directory / 'output', expected_kind=job.execution.kind) + staged = [(uuid5(job.id, f"output-upload:{record['role']}:{record.get('variant') or ''}:{record.get('track') or ''}"), + with_extension(self._artifact_name(name, record), record['suffix']), + artifact_kind(record['suffix']), record) + for record in cache.artifacts()] + for extra_handle, extra_name, extra_kind, record in staged: + self.assets.stage_output(job.projectId, extra_handle, extra_name, + cache.artifact_file(record), expected_kind=extra_kind) # Sibling results or user edits may advance the same spec between our # read and commit. Retry only registration of these already saved bytes; # eligibility is recalculated from each new snapshot, never by resending # the provider request or reusing an obsolete adoption decision. for attempt in range(16): try: - return self._register_output(task, pinned, suffix, handle, name) + return self._register_output(task, pinned, suffix, handle, name, staged) except ProjectError as error: if error.code != 'revision_conflict' or attempt == 15: raise - def _register_output(self, task, pinned, suffix, handle, name): + @staticmethod + def _artifact_name(name, record): + """Asset names stay readable and still distinguish same-role siblings.""" + parts = [part for part in (record['role'], record.get('variant'), (record.get('track') or '').replace(':', '-')) + if part and part != 'primary'] + return f"{name}-{'-'.join(parts)}" if parts else name + + def _register_output(self, task, pinned, suffix, handle, name, staged=()): before = self.projects.snapshot(task['projectId']) job = next(j for j in before.jobs if str(j.id) == task['id']) if job.status == 'succeeded': + known = {asset.id for asset in before.assets} + if any(gateway().upload_asset_id(job.projectId, handle) not in known + for handle, _, _, _ in staged): + raise ProjectError('任务已完成,但附加产物未登记;请核对生成恢复缓存。', 409, code='operation_rejected') return self._result_asset(task, pinned) spec = next(s for s in before.generationSpecs if s.id == job.inputSnapshot.spec.id) origin = next((i for i in before.canvasItems if i.id == job.originItemId), None) command = parse_command(dict(commandId=uuid5(job.id, f'register-result:{job.revision}:{spec.revision}:{origin.revision if origin else 0}'), projectId=job.projectId, type='asset.import', expectedVersions=[version('job', job), version('generation_spec', spec), *([version('canvas_item', origin)] if origin else [])], payload=dict(uploadHandle=handle, name=with_extension(name, suffix), expectedKind=job.execution.kind))) + extras = [(gateway().upload_asset_id(job.projectId, extra_handle), record) for extra_handle, _, _, record in staged] def apply(current, asset): current_job = next(j for j in current.jobs if j.id == job.id) current_spec = next(s for s in current.generationSpecs if s.id == spec.id) @@ -659,6 +680,10 @@ def apply(current, asset): additional = self._additional_item(current, item, asset, current_job) result = ResultVersion(id=uuid5(job.id, 'result'), projectId=job.projectId, specId=spec.id, jobId=job.id, asset=asset_ref(asset), inputFingerprint=job.inputFingerprint) + extra_results = tuple(ResultVersion(id=uuid5(job.id, f"result:{record['role']}:{record.get('variant') or ''}:{record.get('track') or ''}"), + projectId=job.projectId, specId=spec.id, jobId=job.id, inputFingerprint=job.inputFingerprint, + role=record['role'], variant=record.get('variant'), track=record.get('track'), + asset=asset_ref(next(item for item in current.assets if item.id == asset_id))) for asset_id, record in extras) check = self._technical_check(media_record(asset)) completed = Job.model_validate({**current_job.model_dump(), 'status': 'succeeded', 'phase': 'complete', 'recovery': 'done', 'resumeAllowed': False, 'asset': asset_ref(asset), 'adopted': adopt, @@ -671,13 +696,14 @@ def apply(current, asset): editors = tuple(ref for ref in item.editors if ref.kind not in {'layers', 'image_crop'}) if (width, height, binding, editors) != (item.width, item.height, item.binding, item.editors): adopted_item = item.model_copy(update={'binding': binding, 'editors': editors, 'width': width, 'height': height, 'revision': item.revision + 1}) - return current.model_copy(update={'assets': (*current.assets, asset), 'results': (*current.results, result), + return current.model_copy(update={'assets': (*current.assets, asset), 'results': (*current.results, result, *extra_results), 'jobs': tuple(completed if j.id == job.id else j for j in current.jobs), 'canvasItems': (*tuple(adopted_item if item and i.id == item.id else i for i in current.canvasItems), *([additional] if additional else [])), 'generationSpecs': tuple(adopted_spec if s.id == spec.id else s for s in current.generationSpecs)}) provenance = AssetProvenance(source='generated', jobId=job.id, inputFingerprint=job.inputFingerprint, sources=tuple({r.asset.assetId: r.asset for r in job.inputSnapshot.references}.values())) - receipt = self.assets.register(command, source='background', provenance=provenance, apply=apply) + receipt = self.assets.register(command, source='background', provenance=provenance, apply=apply, + staged=tuple((extra_handle, extra_name, extra_kind) for extra_handle, extra_name, extra_kind, _ in staged)) if receipt.status == 'rejected': # The bytes and original job survive; recovery retries local commit, # never the provider submission. A fresh CAS is safe on recovery. diff --git a/packages/core/src/opendirector/application/generation_runtime.py b/packages/core/src/opendirector/application/generation_runtime.py index f58cd6033..97f973695 100644 --- a/packages/core/src/opendirector/application/generation_runtime.py +++ b/packages/core/src/opendirector/application/generation_runtime.py @@ -10,6 +10,7 @@ from opendirector.ports.gateway import gateway from opendirector.integrations.http_settings import MODEL_JOB_CONTEXT from opendirector.integrations.generation_errors import transport_failure +from opendirector.integrations.providers import GeneratedArtifact def _self_hosted_video(task): profile = (task.get('referenceInputs') or {}).get('profile', '') @@ -101,6 +102,20 @@ def recovery(self, task, directory): return 'review' + async def _produce(self, config, task, submitted, result_ready, cache): + """One provider call. Adapters that produce several files answer through generate_all.""" + 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': + 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) + return (GeneratedArtifact(suffix, data),) + async def _run(self, task, pinned, config, mode='submit'): stage = 'save' cache = gateway().results(pinned, task['id']) @@ -157,6 +172,7 @@ async def result_ready(suffix, url): await save() asset = await asyncio.to_thread(self._result_asset, task, pinned) cached = await asyncio.to_thread(cache.data) if asset is None else None + extras = () if asset is None and cached is None: if mode == 'local': raise ProjectError('本地结果缺失,请保留任务并核对;不会重新生成。', 409) @@ -168,13 +184,9 @@ 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 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) + produced = await self._produce(config, task, submitted, result_ready, cache) + suffix, data = produced[0].suffix, produced[0].data + extras = produced[1:] elif cached: suffix, data = cached # Preserve complete bytes before catalog/link writes. Cancellation @@ -187,6 +199,10 @@ async def result_ready(suffix, url): if asset is None and cached is None: task['phase'] = 'save' await asyncio.to_thread(cache.save, suffix, data) + if extras: + await asyncio.to_thread(cache.save_artifacts, [ + {'role': item.role, 'variant': item.variant, 'track': item.track, + 'suffix': item.suffix, 'data': item.data} for item in extras]) await save() try: asset = await asyncio.to_thread(self._commit_output, task, pinned, suffix if asset is None else None, data if asset is None else None) diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 6ee989205..680a05455 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -594,7 +594,7 @@ def command_fingerprint(command: Command) -> str: from opendirector.domain.timeline_errors import TimelineIssueCode -IssueCode = Literal[TimelineIssueCode, 'invalid_input', 'revision_conflict', 'version_required', 'role_restricted', 'canvas_run_layout_group', 'canvas_run_layout_conflict', 'canvas_run_layout_extent', 'canvas_run_layout_shared_object', 'missing_object', 'reference_invalid', 'image_quality_unsupported', +IssueCode = Literal[TimelineIssueCode, 'invalid_input', 'revision_conflict', 'version_required', 'role_restricted', 'canvas_run_layout_group', 'canvas_run_layout_conflict', 'canvas_run_layout_extent', 'canvas_run_layout_shared_object', 'missing_object', 'reference_invalid', 'result_not_adoptable', 'image_quality_unsupported', 'keyframe_unsupported', 'keyframe_mode', 'keyframe_kind', 'keyframe_count', 'keyframe_needs_reference', 'keyframe_time', 'keyframe_image', 'bigmodel_video_model', 'bigmodel_video_output', 'bigmodel_video_image', 'bigmodel_video_frames', 'bigmodel_video_prompt', 'bigmodel_video_cancel', @@ -704,7 +704,7 @@ class CanvasStatusQuery(QueryBase): class JobStatusQuery(QueryBase): - type: Literal['job.status'] = Field(description='Read several generation jobs, optionally waiting for terminal states.') + type: Literal['job.status'] = Field(description='Read several generation jobs, optionally waiting for terminal states. Each delivery lists the adopted output and every further artifact the job produced (audio tracks, subtitles).') objectIds: tuple[UUID, ...] = Field(default=(), max_length=50, description='Generation job IDs; every unfinished project job when empty.') waitSeconds: float = Field(default=0, ge=0, le=300, description='Wait for terminal states; zero returns immediately.') until: Literal['all', 'any'] = Field(default='all', description='Return after every selected job or any job reaches a terminal state.') diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index e3efc5207..87e480432 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -410,6 +410,12 @@ class ResultVersion(ProjectEntity): jobId: UUID = Field(description='Generation job ID.') asset: AssetRef = Field(description='Immutable asset version.') inputFingerprint: Digest = Field(description='Fingerprint of the fixed execution input.') + role: Literal['primary', 'dubbed_video', 'audio_track', 'subtitle'] = Field(default='primary', + description='File this version is; only the primary one is the adopted job output.') + variant: str | None = Field(default=None, exclude_if=lambda value: value is None, + description='Same-role distinction, such as a target and a source subtitle.') + track: str | None = Field(default=None, exclude_if=lambda value: value is None, + description='Separated stem identity, such as speaker:0.') def execution_spec(spec, references, rules): diff --git a/packages/core/src/opendirector/domain/creation/project.py b/packages/core/src/opendirector/domain/creation/project.py index 3d5e4e0a8..b9a51fcd1 100644 --- a/packages/core/src/opendirector/domain/creation/project.py +++ b/packages/core/src/opendirector/domain/creation/project.py @@ -165,13 +165,21 @@ def project_relations(self): acyclic({job.id: [job.previousJobId] for job in self.jobs if job.previousJobId}, 'job attempts') for result in self.results: job = jobs.get(result.jobId) - if job is None or job.status != 'succeeded' or job.inputSnapshot.spec.id != result.specId or job.asset != result.asset or job.inputFingerprint != result.inputFingerprint: + if job is None or job.status != 'succeeded' or job.inputSnapshot.spec.id != result.specId or job.inputFingerprint != result.inputFingerprint: + raise ValueError('Result version must match the completed job and output') + if result.role == 'primary': + matched = job.asset == result.asset + else: + # A job adopts one output and keeps any further files it produced. + matched = any(asset.id == result.asset.assetId and asset.provenance.jobId == job.id for asset in self.assets) + if not matched: raise ValueError('Result version must match the completed job and output') for asset in self.assets: provenance = asset.provenance if provenance.source == 'generated': job = jobs.get(provenance.jobId) - if job is None or job.asset is None or job.asset.assetId != asset.id or job.inputFingerprint != provenance.inputFingerprint: + extra = any(result.asset.assetId == asset.id for result in self.results if result.jobId == provenance.jobId) + if job is None or job.asset is None or job.inputFingerprint != provenance.inputFingerprint or (job.asset.assetId != asset.id and not extra): raise ValueError('Generated asset provenance does not match its job') if provenance.sourceItemId and provenance.sourceItemId not in items: raise ValueError('Edited asset refers to a missing logical source') diff --git a/packages/core/src/opendirector/infrastructure/generation_results.py b/packages/core/src/opendirector/infrastructure/generation_results.py index a2516a494..bce4c938d 100644 --- a/packages/core/src/opendirector/infrastructure/generation_results.py +++ b/packages/core/src/opendirector/infrastructure/generation_results.py @@ -3,6 +3,7 @@ import json import os from pathlib import Path +import re import tempfile from urllib.parse import urlsplit @@ -16,6 +17,18 @@ def _submission_digest(value): return hashlib.sha256(encoded).hexdigest() +ARTIFACT_SUFFIXES = frozenset({'mp3', 'wav', 'm4a', 'ogg', 'flac', 'mp4', 'mov', 'webm', 'srt', 'jsonl'}) + + +def _artifact_key(role, variant, track): + """Identity is the vendor-independent triple, never a position in a list.""" + parts = [role, variant or '', track or ''] + for part in parts: + if not isinstance(part, str) or not re.fullmatch(r'[a-z0-9_:]*', part): + raise ValueError('Artifact identity is invalid.') + return '-'.join(parts) + + class GenerationResults: def __init__(self, directory, task_id): self.root = child(Path(directory), '.generation-results') @@ -78,6 +91,58 @@ def data(self): raise ProjectError('生成恢复缓存超过大小限制。', 409) return metadata['suffix'], path.read_bytes() + def artifact_file(self, record): + """Private path of one extra file of this task; never exposed in receipts.""" + return child(self.directory, f"artifact-{_artifact_key(record['role'], record.get('variant'), record.get('track'))}") + + def artifacts(self): + """Extra files produced beside the adopted output, in provider order.""" + path = child(self.directory, 'artifacts.json') + if not path.exists(): + return () + try: + records = read_json(path)['artifacts'] + if not isinstance(records, list): + raise TypeError() + for record in records: + if not isinstance(record, dict) or not isinstance(record.get('role'), str) or not record['role']: + raise TypeError() + _artifact_key(record['role'], record.get('variant'), record.get('track')) + if record.get('suffix') not in ARTIFACT_SUFFIXES: + raise ValueError() + return tuple(records) + except (KeyError, TypeError, ValueError): + raise ProjectError('生成恢复缓存无效,请保留原文件并核对任务。', 409) from None + + def save_artifacts(self, records): + """Persist the files, then the index that names them.""" + prepared = [] + for record in records: + data = record['data'] + if len(data) > MAX_ASSET_BYTES: + raise ProjectError('生成结果超过 50 MB,无法保存到项目。', 413) + identity = {'role': record['role'], 'variant': record.get('variant'), 'track': record.get('track'), + 'suffix': record['suffix']} + if identity['suffix'] not in ARTIFACT_SUFFIXES: + raise ProjectError('生成产物的文件类型无法保存到项目。', 415) + try: + self._prepare() + target = self.artifact_file(identity) + except (KeyError, ValueError): + raise ProjectError('生成产物的标识无效,无法保存到项目。', 409) from None + fd, temporary = tempfile.mkstemp(prefix='.artifact-', dir=self.directory) + try: + with os.fdopen(fd, 'wb') as stream: + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, target) + finally: + Path(temporary).unlink(missing_ok=True) + prepared.append({key: value for key, value in identity.items() if value is not None}) + self._prepare() + write_json(child(self.directory, 'artifacts.json'), {'artifacts': prepared}) + def save(self, suffix, data): if len(data) > MAX_ASSET_BYTES: raise ProjectError('生成结果超过 50 MB,无法保存到项目。', 413) @@ -102,7 +167,9 @@ 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', 'submission.json'): + for record in self.artifacts(): + self.artifact_file(record).unlink(missing_ok=True) + for name in ('output', 'result.json', 'submission.json', 'artifacts.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/providers.py b/packages/core/src/opendirector/integrations/providers.py index 4c9eacbe4..d098a25cd 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -2,6 +2,7 @@ import asyncio import base64 import json +from typing import NamedTuple from urllib.parse import quote, urlsplit import httpx @@ -29,6 +30,26 @@ from opendirector.media.probe import require_ffprobe +class GeneratedArtifact(NamedTuple): + """One produced file. Index 0 of a generation result is the adopted output.""" + + suffix: str + data: bytes + role: str = 'primary' + variant: str | None = None + track: str | None = None + + +ARTIFACT_KINDS = {'mp4': 'video', 'mov': 'video', 'webm': 'video', + 'mp3': 'audio', 'wav': 'audio', 'm4a': 'audio', 'ogg': 'audio', 'flac': 'audio', + 'srt': 'text', 'jsonl': 'text'} + + +def artifact_kind(suffix): + """Kind is declared per produced suffix, never guessed from the request.""" + return ARTIFACT_KINDS.get(suffix) + + class GenerationProviders(VolcengineGeneration): """Protocol adapters, plus dedicated adapters for vLLM-Omni MiniMax-H3 and Z-Image-Turbo profiles.""" @@ -132,6 +153,11 @@ async def resume_result(self, config, suffix, url): except (httpx.InvalidURL, ValueError, TypeError, KeyError, AttributeError): raise protocol_failure('download') from None + async def generate_all(self, config, task, submitted, *, result_ready=None, recovery_cache=None): + """Adapters that produce several files override this; the default delivers one.""" + suffix, data = await self.generate(config, task, submitted, result_ready=result_ready, recovery_cache=recovery_cache) + return (GeneratedArtifact(suffix, data),) + 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) diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 31c4dbdc1..40df62ed1 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4730,6 +4730,7 @@ "canvas_run_layout_shared_object", "missing_object", "reference_invalid", + "result_not_adoptable", "image_quality_unsupported", "keyframe_unsupported", "keyframe_mode", @@ -9498,7 +9499,7 @@ }, "type": { "const": "job.status", - "description": "Read several generation jobs, optionally waiting for terminal states.", + "description": "Read several generation jobs, optionally waiting for terminal states. Each delivery lists the adopted output and every further artifact the job produced (audio tracks, subtitles).", "title": "Type", "type": "string" }, @@ -15113,6 +15114,44 @@ "pattern": "^[0-9a-f]{64}$", "title": "Inputfingerprint", "type": "string" + }, + "role": { + "default": "primary", + "description": "File this version is; only the primary one is the adopted job output.", + "enum": [ + "primary", + "dubbed_video", + "audio_track", + "subtitle" + ], + "title": "Role", + "type": "string" + }, + "variant": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Same-role distinction, such as a target and a source subtitle.", + "title": "Variant" + }, + "track": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Separated stem identity, such as speaker:0.", + "title": "Track" } }, "required": [ @@ -25013,6 +25052,7 @@ "canvas_run_layout_shared_object", "missing_object", "reference_invalid", + "result_not_adoptable", "image_quality_unsupported", "keyframe_unsupported", "keyframe_mode", @@ -29961,7 +30001,7 @@ }, "type": { "const": "job.status", - "description": "Read several generation jobs, optionally waiting for terminal states.", + "description": "Read several generation jobs, optionally waiting for terminal states. Each delivery lists the adopted output and every further artifact the job produced (audio tracks, subtitles).", "title": "Type", "type": "string" }, @@ -35736,6 +35776,44 @@ "pattern": "^[0-9a-f]{64}$", "title": "Inputfingerprint", "type": "string" + }, + "role": { + "default": "primary", + "description": "File this version is; only the primary one is the adopted job output.", + "enum": [ + "primary", + "dubbed_video", + "audio_track", + "subtitle" + ], + "title": "Role", + "type": "string" + }, + "variant": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Same-role distinction, such as a target and a source subtitle.", + "title": "Variant" + }, + "track": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Separated stem identity, such as speaker:0.", + "title": "Track" } }, "required": [ @@ -35745,7 +35823,8 @@ "specId", "jobId", "asset", - "inputFingerprint" + "inputFingerprint", + "role" ], "title": "ResultVersion", "type": "object" diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 02686afae..2c87584f3 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -513,7 +513,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -1528,6 +1528,9 @@ export interface ResultVersionInput extends ProjectEntityInput { readonly jobId: string; readonly asset: AssetRefInput; readonly inputFingerprint: string; + readonly role?: "primary" | "dubbed_video" | "audio_track" | "subtitle"; + readonly variant?: string | null; + readonly track?: string | null; } export interface SegmentRunAnchorInput { @@ -2570,7 +2573,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId: string | null; readonly field: string | null; @@ -3584,6 +3587,9 @@ export interface ResultVersion extends ProjectEntity { readonly jobId: string; readonly asset: AssetRef; readonly inputFingerprint: string; + readonly role: "primary" | "dubbed_video" | "audio_track" | "subtitle"; + readonly variant?: string | null; + readonly track?: string | null; } export interface SegmentRunAnchor { diff --git a/tests/fixtures/creation-project.json b/tests/fixtures/creation-project.json index a040daa0c..5a7f6c660 100644 --- a/tests/fixtures/creation-project.json +++ b/tests/fixtures/creation-project.json @@ -1058,7 +1058,8 @@ "fingerprint": "sha256:000000000000000000000000000000000000000000000000000000000000000f", "kind": "image" }, - "inputFingerprint": "e74318d3b8ecd3052b04b10df4a542b9f51c0456d2b05cd7dea1223e96fc0474" + "inputFingerprint": "e74318d3b8ecd3052b04b10df4a542b9f51c0456d2b05cd7dea1223e96fc0474", + "role": "primary" } ], "eventCursor": 0, diff --git a/tests/test_result_artifacts.py b/tests/test_result_artifacts.py new file mode 100644 index 000000000..754bdd4e5 --- /dev/null +++ b/tests/test_result_artifacts.py @@ -0,0 +1,247 @@ +"""Acceptance: one job delivers its adopted output plus every file it produced.""" +import asyncio +from io import BytesIO +from pathlib import Path +from uuid import UUID, uuid4, uuid5 +import wave + +from PIL import Image +import pytest + +from opendirector.application.creation_assets import CreationAssets +from opendirector.application.creation_canvas import CreationCanvas +from opendirector.application.creation_generation import CreationGeneration +from opendirector.domain.assets import MAX_ASSET_BYTES +from opendirector.domain.creation.commands import JobStatusQuery, parse_command +from opendirector.domain.creation.project import ProjectSnapshot +from opendirector.domain.projects import ProjectError +from opendirector.infrastructure.generation_results import GenerationResults +from opendirector.infrastructure.model_configs import ModelConfigs +from opendirector.integrations.providers import GeneratedArtifact, GenerationProviders +from opendirector.ports.gateway import gateway +from test_creation_canvas_service import project, media, send, ver +from test_creation_generation_service import anyio_backend, Provider + + +pytestmark = pytest.mark.cpu + + +def wav(seconds=0.2, rate=8000): + output = BytesIO() + with wave.open(output, 'wb') as stream: + stream.setnchannels(1) + stream.setsampwidth(2) + stream.setframerate(rate) + stream.writeframes(b'\x00\x00' * int(rate * seconds)) + return output.getvalue() + + +class Fanout(Provider): + """A provider whose adapter returns the output and the files beside it.""" + + def __init__(self, extras=()): + super().__init__() + self.extras = extras + + async def generate_all(self, config, task, submitted, *, result_ready=None, recovery_cache=None): + self.calls.append(task) + output = BytesIO() + Image.new('RGB', (32, 24), 'red').save(output, 'PNG') + return (GeneratedArtifact('png', output.getvalue()), *self.extras) + + +def runtime(project, provider): + store, _, _ = project + configs = ModelConfigs(store.local.repository) + config = configs.save('image', 'http://127.0.0.1:12345/v1', 'test-image', '', + connection_type='self_hosted', protocol='openai', auth_mode='none') + return CreationGeneration(store, configs, provider), config + + +def configure(project, config): + store, pid, session = project + target, spec = media(project, 'image') + changed = spec.model_copy(update={'prompt': 'Use the source', 'modelConfigId': UUID(config['id'])}) + assert send(store, pid, 'generationSpec.update', session=session, + versions=[ver('generation_spec', spec)], spec=changed).status == 'applied' + return target, store.snapshot(pid).generationSpecs[-1] + + +async def start(project, provider): + store, pid, session = project + runner, config = runtime(project, provider) + target, spec = configure(project, config) + command = parse_command(dict(commandId=uuid4(), projectId=pid, type='generation.submit', + expectedVersions=[ver('generation_spec', spec), ver('canvas_item', target)], + payload=dict(specId=spec.id, expectedSpecRevision=spec.revision, originItemId=target.id, + adoptionPolicy='if_current'))) + assert (await runner.execute(command, session=session)).status == 'accepted' + return runner, store.snapshot(pid).jobs[-1].id + + +async def run(project, provider): + store, pid, _ = project + runner, _ = await start(project, provider) + await settle(runner) + return store.snapshot(pid) + + +async def settle(runner, timeout=30): + await asyncio.wait_for(asyncio.gather(*(job.future for job in list(runner.jobs.values()))), timeout) + + +@pytest.mark.anyio +async def test_output_and_its_siblings_commit_together(project): + extra = GeneratedArtifact('wav', wav(), role='audio_track', track='speaker:0') + store, pid, _ = project + snapshot = await run(project, Fanout((extra,))) + job = snapshot.jobs[-1] + assert job.status == 'succeeded' + primary = next(result for result in snapshot.results if result.jobId == job.id and result.role == 'primary') + tracks = [result for result in snapshot.results if result.jobId == job.id and result.role == 'audio_track'] + assert primary.asset == job.asset + assert [result.track for result in tracks] == ['speaker:0'] + assert tracks[0].asset.assetId != primary.asset.assetId + assert tracks[0].id == uuid5(job.id, 'result:audio_track::speaker:0') + extra_handle = uuid5(job.id, 'output-upload:audio_track::speaker:0') + assert tracks[0].asset.assetId == gateway().upload_asset_id(job.projectId, extra_handle) + assert snapshot.assets[-1].provenance.jobId == job.id + canvas = CreationCanvas(store) + delivery = canvas.job_states(pid, (job.id,))['jobs'][0]['delivery'] + assert [(item['role'], item['track']) for item in delivery['artifacts']] == [('audio_track', 'speaker:0')] + assert delivery['artifacts'][0]['asset'] == tracks[0].asset.model_dump(mode='json') + state = await canvas.query(JobStatusQuery(type='job.status', queryId=uuid4(), projectId=pid, objectIds=(job.id,))) + queried = state['jobs'][0]['delivery'] + assert queried['artifacts'] == delivery['artifacts'] + + +@pytest.mark.anyio +async def test_extra_files_are_never_adopted_in_place_of_the_output(project): + extra = GeneratedArtifact('wav', wav(), role='audio_track', track='speaker:0') + snapshot = await run(project, Fanout((extra,))) + track = next(result for result in snapshot.results if result.role == 'audio_track') + store, pid, session = project + current = store.snapshot(pid) + spec = next(s for s in current.generationSpecs if s.id == track.specId) + receipt = send(store, pid, 'result.select', session=session, versions=[ver('generation_spec', spec)], + specId=spec.id, resultId=track.id) + assert receipt.status == 'rejected' + assert any(issue.code == "result_not_adoptable" for issue in receipt.issues) + assert store.snapshot(pid).generationSpecs[0].currentResultId != track.id + + +@pytest.mark.anyio +async def test_each_same_role_sibling_keeps_its_own_handle(project): + extras = (GeneratedArtifact('wav', wav(), role='audio_track', track='speaker:0'), + GeneratedArtifact('wav', wav(0.3), role='audio_track', track='speaker:1')) + snapshot = await run(project, Fanout(extras)) + job = snapshot.jobs[-1] + tracks = sorted((result for result in snapshot.results if result.role == 'audio_track'), key=lambda r: r.track) + assert [result.track for result in tracks] == ['speaker:0', 'speaker:1'] + ids = {result.asset.assetId for result in tracks} + assert len(ids) == 2 + + +def test_an_unusable_extra_never_reaches_the_project(tmp_path): + cache = GenerationResults(tmp_path, str(uuid4())) + with pytest.raises(ProjectError) as rejected: + cache.save_artifacts([{'role': 'audio_track', 'variant': None, 'track': 'speaker:0', 'suffix': 'xyz', 'data': b''}]) + assert rejected.value.status == 415 + with pytest.raises(ProjectError) as oversized: + cache.save_artifacts([{'role': 'audio_track', 'variant': None, 'track': 'speaker:0', 'suffix': 'wav', + 'data': b'\0' * (MAX_ASSET_BYTES + 1)}]) + assert oversized.value.status == 413 + assert cache.artifacts() == () + + +def test_artifact_index_survives_a_restart_and_clears_with_the_task(tmp_path): + task = str(uuid4()) + cache = GenerationResults(tmp_path, task) + cache.save_artifacts([{'role': 'subtitle', 'variant': 'target_srt', 'track': None, 'suffix': 'srt', + 'data': '1\n00:00:00,000 --> 00:00:01,000\nHallo\n'.encode()}]) + reopened = GenerationResults(tmp_path, task) + record, = reopened.artifacts() + assert (record['role'], record['variant'], record['suffix']) == ('subtitle', 'target_srt', 'srt') + assert reopened.artifact_file(record).read_text() == '1\n00:00:00,000 --> 00:00:01,000\nHallo\n' + reopened.clear() + assert reopened.artifacts() == () + assert not reopened.artifact_file(record).exists() + + +def test_artifact_identity_cannot_leave_the_cache_directory(tmp_path): + cache = GenerationResults(tmp_path, str(uuid4())) + with pytest.raises(ProjectError) as rejected: + cache.save_artifacts([{'role': '../../escape', 'variant': None, 'track': None, 'suffix': 'wav', 'data': b''}]) + assert rejected.value.status == 409 + + +@pytest.mark.anyio +async def test_a_provider_without_fan_out_still_delivers_one_file(): + class Single(Provider): + async def generate(self, config, task, submitted, **kwargs): + return 'md', b'Actual generated text' + + produced = await GenerationProviders.generate_all(Single(), None, {}, None) + assert [(item.role, item.suffix, item.data) for item in produced] == [('primary', 'md', b'Actual generated text')] + + +def test_stored_projects_without_a_role_still_load(): + value = ProjectSnapshot.model_validate({'format': 'opendirector-project', 'formatVersion': 2, + 'project': {'id': str(uuid4()), 'name': 'Old'}, 'results': [], 'jobs': [], 'assets': []}) + assert value.results == () + + +@pytest.mark.anyio +async def test_an_interrupted_save_replays_every_file_once(project, monkeypatch): + extra = GeneratedArtifact('wav', wav(), role='audio_track', track='speaker:0') + store, pid, _ = project + original = CreationGeneration._register_output + + def broken(self, *args, **kwargs): + raise ProjectError('磁盘写入被中断。', 503) + + monkeypatch.setattr(CreationGeneration, '_register_output', broken) + runner, job_id = await start(project, Fanout((extra,))) + await settle(runner) + failed = store.snapshot(pid).jobs[-1] + assert (failed.status, failed.recovery, failed.asset) == ('interrupted', 'local', None) + cache = gateway().results(str(runner.directory(pid)), str(job_id)) + assert [record['track'] for record in cache.artifacts()] == ['speaker:0'] + + monkeypatch.setattr(CreationGeneration, '_register_output', original) + await runner.recover(pid, job_id) + await settle(runner) + snapshot = store.snapshot(pid) + job = next(item for item in snapshot.jobs if item.id == job_id) + assert job.status == 'succeeded' + delivered = [result for result in snapshot.results if result.jobId == job_id] + assert sorted(result.role for result in delivered) == ['audio_track', 'primary'] + assert len({result.asset.assetId for result in delivered}) == 2 + + +@pytest.mark.anyio +async def test_a_finished_job_never_hides_an_unregistered_sibling(project): + store, pid, _ = project + runner, job_id = await start(project, Fanout((GeneratedArtifact('wav', wav(), role='audio_track', track='speaker:0'),))) + await settle(runner) + job = next(item for item in store.snapshot(pid).jobs if item.id == job_id) + pinned = str(runner.directory(pid)) + cache = gateway().results(pinned, str(job_id)) + cache.save_artifacts([{'role': 'audio_track', 'variant': None, 'track': 'speaker:1', 'suffix': 'wav', 'data': wav(0.3)}]) + task = runner.task(job) + assert cache.artifacts() + with pytest.raises(ProjectError) as failure: + runner._commit_output(task, pinned, None, None) + assert failure.value.code == 'operation_rejected' + + +@pytest.mark.anyio +async def test_a_subtitle_sidecar_lands_as_a_readable_text_asset(project): + store, pid, _ = project + subtitle = '1\n00:00:00,000 --> 00:00:01,000\nHallo\n' + snapshot = await run(project, Fanout((GeneratedArtifact('srt', subtitle.encode(), role='subtitle', variant='target_srt'),))) + result = next(item for item in snapshot.results if item.role == 'subtitle') + stream, asset = CreationAssets(store).open_media(pid, result.asset.assetId) + with stream: + assert stream.read().decode() == subtitle + assert (asset.kind, asset.name) == ('text', 'Use the source-subtitle-target_srt.srt') From bc663856f7986c4c703215e0e4e1396020ecdbd1 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 11:31:15 +0800 Subject: [PATCH 07/58] [feat] audio: keep every file Seed Audio returns ## summary The Seed Audio adapter now names every file it produces, so the persistence layer added in the previous commit receives more than a bare `(suffix, bytes)`. `dubbing_artifacts()` and the renamed `audio_artifacts()` answer with `(role, url, suffix, variant, track)` tuples. The suffix comes from the URL the vendor returned, restricted to an allow-list; subtitles are told apart by `_`; audio tracks are counted per `type` so two speakers cannot claim the same identity. Dubbing requests every subtitle the response can carry, so the parsed variants are reachable rather than theoretical. `VolcengineGeneration.generate_all()` collects those siblings through an optional `extra_ready` callback and downloads them itself, which keeps the persistence layer free of URLs. Providers without fan-out keep the single-file path, and the profile adapters that inherit the Volcengine `generate_all()` never reach the callback. ## tests - `python3 -m pytest tests -q -m "not browser"` -> 3552 passed, 133 skipped - `tests/test_seed_audio.py` -> 35 passed, including the multi-track job that adopts the primary audio and stores `speaker:0` beside it - `npx tsc --noEmit` -> no output; `node --test tests/*.test.ts` -> 0 fail; `check:i18n` -> 3828 keys, 0 problems --- docs/development/seed-audio-1-5-probe.md | 23 +++--- .../opendirector/integrations/providers.py | 11 ++- .../opendirector/integrations/seed_audio.py | 69 ++++++++++------ .../opendirector/integrations/volcengine.py | 49 ++++++++++-- tests/test_result_artifacts.py | 4 +- tests/test_seed_audio.py | 78 +++++++++++++++---- 6 files changed, 177 insertions(+), 57 deletions(-) diff --git a/docs/development/seed-audio-1-5-probe.md b/docs/development/seed-audio-1-5-probe.md index 329eaea1e..4c1bbc24d 100644 --- a/docs/development/seed-audio-1-5-probe.md +++ b/docs/development/seed-audio-1-5-probe.md @@ -29,16 +29,20 @@ transports and the result parsing. 1.5 gets its own `ark-content` preset on `/api/v3`. `VolcengineGeneration.validate` refuses the wrong base with `seed_audio_base_url` instead of forwarding a confusing 404. -- **Video references and video dubbing are out of scope here.** Inline video is - rejected and a project asset has no public URL. Implementing either needs a - publishing step first; the adapter therefore publishes only operations whose - inputs a project can supply today (`text2audio`). +- **A video reference must be published before the request.** Inline video is + rejected, so dubbing uploads the project asset through the configured TOS + storage and presigns it. Without that storage the adapter refuses the + submission instead of sending an unusable `data:` URL. - **Results are parsed by `content.audios[]`, not `audio_url`.** A response without a usable URL is a protocol failure, so it is never reported as a completed job. -- **One artifact is one file.** Multi-track separation returns several URLs in - one response, which the current one-asset job model cannot store; that is a - separate change. +- **One call can produce several files.** Subtitle dubbing answers with the + dubbed video plus tracks and subtitles, so a job stores every file it + produced under `(role, variant, track)` in a single commit. The adopted output + stays the primary one; `result.select` refuses to adopt a sibling, and the + job projection lists the rest. Which subtitle entries a live dubbing response + actually carries is still unverified, so a missing entry never fails a job + that delivered its video. - The service is synchronous, so a failed submission has no task id to resume: the existing `submission_unknown → review` rule stays correct and nothing is resubmitted automatically. @@ -51,8 +55,9 @@ transports and the result parsing. - The composer renders the operation mode only; the prosody offsets are reachable through the command contract (and therefore the agent), not yet through dedicated controls. -- Not accepted: references, separation, dubbing, multi-artifact results and - custom voices. Each needs a separate change, as the probe explains. +- Not accepted yet: track separation (`taskType=separation` is refused with + `audio_task_unsupported`), and custom voices beyond the reference-audio path. + Each needs a separate change, as the probe explains. ## Measured output matrix diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index d098a25cd..e99f44188 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -154,11 +154,15 @@ async def resume_result(self, config, suffix, url): raise protocol_failure('download') from None async def generate_all(self, config, task, submitted, *, result_ready=None, recovery_cache=None): - """Adapters that produce several files override this; the default delivers one.""" + """Only the Volcengine family can return more than one file per call.""" + if not config or config.get('protocol') in {None, 'volcengine'}: + return await super().generate_all(config, task, submitted, result_ready=result_ready, + recovery_cache=recovery_cache) suffix, data = await self.generate(config, task, submitted, result_ready=result_ready, recovery_cache=recovery_cache) return (GeneratedArtifact(suffix, data),) - async def generate(self, config, task, submitted, *, result_ready=None, recovery_cache=None): + async def generate(self, config, task, submitted, *, result_ready=None, recovery_cache=None, + 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 input_rules(config)['profile'] == 'bigmodel-glm-image': @@ -197,7 +201,8 @@ async def generate(self, config, task, submitted, *, result_ready=None, recovery watermark=task['parameters'].get('watermark_enabled', True)) return result.suffix, result.data if config.get('protocol') in {None, 'volcengine'} or task['kind'] == 'text': - return await super().generate(config, task, submitted, result_ready=result_ready) + return await super().generate(config, task, submitted, result_ready=result_ready, + extra_ready=extra_ready) kind, stage = task['kind'], 'submit' secrets = (config.get('apiKey', ''),) try: diff --git a/packages/core/src/opendirector/integrations/seed_audio.py b/packages/core/src/opendirector/integrations/seed_audio.py index 8398c5748..953a8aa05 100644 --- a/packages/core/src/opendirector/integrations/seed_audio.py +++ b/packages/core/src/opendirector/integrations/seed_audio.py @@ -1,7 +1,12 @@ """Volcengine Ark Seed Audio 1.5 content generation.""" +from urllib.parse import urlsplit + from opendirector.domain.rule_facts import SEED_AUDIO_MODEL_PREFIX as MODEL_PREFIX +AUDIO_SUFFIXES = frozenset({'mp3', 'wav', 'm4a', 'ogg', 'flac'}) +TEXT_SUFFIXES = frozenset({'srt', 'jsonl'}) + def is_seed_audio(model_id): return isinstance(model_id, str) and model_id.startswith(MODEL_PREFIX) @@ -32,39 +37,57 @@ def dubbing_body(config, video_url, parameters, subtitle_url=None): 'content': [{'type': 'video_url', 'role': 'dubbing_video', 'video_url': {'url': video_url}}], 'dubbing_config': config_body, - 'include': ['video_url', 'subtitles.srt']} + 'include': ['video_url', 'subtitles.srt', 'subtitles.jsonl', + 'subtitles_source.srt', 'subtitles_source.jsonl']} return body +def artifact_suffix(url, allowed, default): + """The suffix a produced file carries, read from the URL the vendor returned.""" + suffix = urlsplit(url).path.rsplit('.', 1)[-1].lower() + return suffix if suffix in allowed else default + + +def _tracks(entries, artifacts): + counts = {} + for entry in entries or []: + url = entry.get('url') if isinstance(entry, dict) else None + if not isinstance(url, str) or not url: + raise ValueError('Seed Audio artifact has no URL') + track = entry.get('type') if isinstance(entry.get('type'), str) and entry['type'] else 'composite' + index = counts.get(track, 0) + counts[track] = index + 1 + artifacts.append(('audio_track', url, artifact_suffix(url, AUDIO_SUFFIXES, 'mp3'), None, + f'{track}:{index}')) + + def dubbing_artifacts(value): - """The dubbed video, the extracted track and the subtitles, in that order.""" + """The dubbed video, then every track and subtitle the same call produced.""" content = value.get('content') or {} video = content.get('video_url') if not isinstance(video, str) or not video: raise ValueError('Seed Audio returned no dubbed video') - artifacts = [('dubbed_video', video)] - for audio in content.get('audios') or []: - url = audio.get('url') if isinstance(audio, dict) else None - if isinstance(url, str) and url: - artifacts.append(('audio_track', url)) - break - for subtitle in content.get('subtitles') or []: - url = subtitle.get('url') if isinstance(subtitle, dict) else None - if isinstance(url, str) and url: - artifacts.append(('subtitle', url)) - break + artifacts = [('primary', video, artifact_suffix(video, {'mp4', 'mov', 'webm'}, 'mp4'), None, None)] + _tracks(content.get('audios'), artifacts) + for entry in content.get('subtitles') or []: + url = entry.get('url') if isinstance(entry, dict) else None + if not isinstance(url, str) or not url: + raise ValueError('Seed Audio subtitle has no URL') + scope = 'source' if str(entry.get('source') or entry.get('type') or '').lower() == 'source' else 'target' + suffix = str(entry.get('format') or '').lower() or artifact_suffix(url, TEXT_SUFFIXES, 'srt') + artifacts.append(('subtitle', url, suffix, f'{scope}_{suffix}', None)) return tuple(artifacts) -def artifact_urls(value): - """Artifact URLs in response order; the first one is the primary result.""" - audios = value['content']['audios'] +def audio_artifacts(value): + """Every generated track; the first one is the adopted output.""" + audios = (value.get('content') or {}).get('audios') if not isinstance(audios, list) or not audios: raise ValueError('Seed Audio returned no audio artifact') - urls = [] - for audio in audios: - url = audio.get('url') if isinstance(audio, dict) else None - if not isinstance(url, str) or not url: - raise ValueError('Seed Audio artifact has no URL') - urls.append(url) - return tuple(urls) + first = audios[0] + url = first.get('url') if isinstance(first, dict) else None + if not isinstance(url, str) or not url: + raise ValueError('Seed Audio artifact has no URL') + artifacts = [('primary', url, artifact_suffix(url, AUDIO_SUFFIXES, 'mp3'), None, None)] + _tracks(audios[1:], artifacts) + return tuple(artifacts) diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index 55791ac19..260fd7ad2 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -18,7 +18,7 @@ from opendirector.integrations.chat_completions import ChatCompletions, chat_payload from opendirector.integrations.reference_inputs import generation_references, request_size from opendirector.integrations.generation_errors import checked, protocol_failure, provider_failure, transport_failure -from opendirector.integrations.seed_audio import (artifact_urls as seed_audio_artifacts, is_seed_audio, +from opendirector.integrations.seed_audio import (audio_artifacts as seed_audio_artifacts, is_seed_audio, dubbing_artifacts as seed_audio_dubbing_artifacts, dubbing_body as seed_audio_dubbing_body, request_body as seed_audio_body) from opendirector.integrations import tos_transfer @@ -147,7 +147,36 @@ async def generate_image(self, config, prompt, parameters, refs, *, request_byte except (ValueError, TypeError, KeyError, IndexError, AttributeError): raise protocol_failure(stage) from None - async def generate(self, config, task, submitted, *, result_ready=None): + async def generate_all(self, config, task, submitted, *, result_ready=None, recovery_cache=None): + """Collect the files beside the primary one instead of dropping them.""" + from opendirector.integrations.providers import GeneratedArtifact + + extras = [] + + async def extra_ready(role, variant, track, suffix, url): + extras.append((role, variant, track, suffix, url)) + + suffix, data = await self.generate(config, task, submitted, result_ready=result_ready, + extra_ready=extra_ready) + if not extras: + return (GeneratedArtifact(suffix, data),) + produced = [GeneratedArtifact(suffix, data)] + try: + async with httpx.AsyncClient(event_hooks=MODEL_HTTP_HOOKS, transport=self.transport, + timeout=httpx.Timeout(240, connect=15), follow_redirects=False) as client: + for role, variant, track, extra_suffix, url in extras: + produced.append(GeneratedArtifact( + extra_suffix, await self._download(client, url, secrets=(config['apiKey'],)), + role=role, variant=variant, track=track)) + except httpx.TimeoutException: + raise transport_failure('download', timeout=True) from None + except httpx.HTTPError: + raise transport_failure('download') from None + except (httpx.InvalidURL, ValueError, TypeError, KeyError, AttributeError): + raise protocol_failure('download') from None + return tuple(produced) + + async def generate(self, config, task, submitted, *, result_ready=None, extra_ready=None): kind = task["kind"] if kind == "text": return await self._text(config, task) @@ -257,8 +286,11 @@ async def query(): stage = 'download' artifacts = seed_audio_dubbing_artifacts(value) if result_ready: - await result_ready('mp4', artifacts[0][1]) - return "mp4", await self._download(client, artifacts[0][1], secrets=secrets) + await result_ready(artifacts[0][2], artifacts[0][1]) + if extra_ready: + for role, url, extra_suffix, variant, track in artifacts[1:]: + await extra_ready(role, variant, track, extra_suffix, url) + return artifacts[0][2], await self._download(client, artifacts[0][1], secrets=secrets) if kind == "audio" and is_seed_audio(config["modelId"]): payload = seed_audio_body(config, prompt, task["parameters"], prepared['images'], prepared['audios']) @@ -267,10 +299,13 @@ async def query(): headers=headers, json=payload) as response: value = json.loads(await bounded(response, stage=stage, secrets=secrets)) stage = 'download' - urls = seed_audio_artifacts(value) + artifacts = seed_audio_artifacts(value) if result_ready: - await result_ready(payload['output_format'], urls[0]) - return payload['output_format'], await self._download(client, urls[0], secrets=secrets) + await result_ready(payload['output_format'], artifacts[0][1]) + if extra_ready: + for role, url, extra_suffix, variant, track in artifacts[1:]: + await extra_ready(role, variant, track, extra_suffix, url) + return payload['output_format'], await self._download(client, artifacts[0][1], secrets=secrets) if kind == "audio": url = endpoint(config["url"], "/tts/unidirectional") headers = {"X-Api-Key": config["apiKey"], "X-Api-Resource-Id": "seed-tts-2.0", "X-Api-Request-Id": str(uuid4())} diff --git a/tests/test_result_artifacts.py b/tests/test_result_artifacts.py index 754bdd4e5..4e7d91fde 100644 --- a/tests/test_result_artifacts.py +++ b/tests/test_result_artifacts.py @@ -177,11 +177,11 @@ def test_artifact_identity_cannot_leave_the_cache_directory(tmp_path): @pytest.mark.anyio async def test_a_provider_without_fan_out_still_delivers_one_file(): - class Single(Provider): + class Single(GenerationProviders): async def generate(self, config, task, submitted, **kwargs): return 'md', b'Actual generated text' - produced = await GenerationProviders.generate_all(Single(), None, {}, None) + produced = await Single(None).generate_all(None, {}, None) assert [(item.role, item.suffix, item.data) for item in produced] == [('primary', 'md', b'Actual generated text')] diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index c84853dbc..847506860 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -15,7 +15,7 @@ from opendirector.domain.creation.models import InputRules, ModelConfigPublic from opendirector.domain.input_rules import input_rules from opendirector.domain.projects import ProjectError -from opendirector.integrations.seed_audio import (artifact_urls, dubbing_artifacts, dubbing_body, +from opendirector.integrations.seed_audio import (audio_artifacts, dubbing_artifacts, dubbing_body, request_body) from opendirector.integrations.volcengine import VolcengineGeneration from test_creation_contracts import entity, model as public_model @@ -85,13 +85,15 @@ def test_request_body_carries_only_the_accepted_prosody_controls(): def test_incomplete_artifact_lists_are_rejected(): with pytest.raises(ValueError): - artifact_urls({'content': {'audios': []}}) + audio_artifacts({'content': {'audios': []}}) with pytest.raises(ValueError): - artifact_urls({'content': {'audios': [{}]}}) - with pytest.raises(KeyError): - artifact_urls({'content': {}}) - assert artifact_urls({'content': {'audios': [{'url': 'https://a/1.mp3'}, - {'url': 'https://a/2.mp3'}]}}) == ('https://a/1.mp3', 'https://a/2.mp3') + audio_artifacts({'content': {'audios': [{}]}}) + with pytest.raises(ValueError): + audio_artifacts({'content': {}}) + assert audio_artifacts({'content': {'audios': [{'url': 'https://a/1.mp3'}, + {'url': 'https://a/2.wav', 'type': 'speaker'}]}}) == ( + ('primary', 'https://a/1.mp3', 'mp3', None, None), + ('audio_track', 'https://a/2.wav', 'wav', None, 'speaker:0')) def test_agent_plan_base_is_refused_before_any_request(): @@ -271,17 +273,67 @@ def test_dubbing_carries_the_video_and_language_without_text(tmp_path): assert body['content'] == [{'type': 'video_url', 'role': 'dubbing_video', 'video_url': {'url': 'https://storage.example/od/clip.mp4'}}] assert body['dubbing_config'] == {'target_language': 'zh', 'source_language': 'en'} - assert body['include'] == ['video_url', 'subtitles.srt'] + assert body['include'] == ['video_url', 'subtitles.srt', 'subtitles.jsonl', + 'subtitles_source.srt', 'subtitles_source.jsonl'] assert 'text' not in body def test_dubbing_artifacts_keep_the_video_track_and_subtitle_order(): artifacts = dubbing_artifacts({'content': {'video_url': 'https://a/dubbed.mp4', - 'audios': [{'url': 'https://a/track.wav'}], - 'subtitles': [{'format': 'srt', 'url': 'https://a/line.srt'}]}}) - assert artifacts == (('dubbed_video', 'https://a/dubbed.mp4'), - ('audio_track', 'https://a/track.wav'), - ('subtitle', 'https://a/line.srt')) + 'audios': [{'url': 'https://a/track.wav', 'type': 'speaker'}, + {'url': 'https://a/music.mp3', 'type': 'bgm'}], + 'subtitles': [{'format': 'srt', 'url': 'https://a/line.srt'}, + {'source': 'source', 'url': 'https://a/original.srt'}]}}) + assert artifacts == (('primary', 'https://a/dubbed.mp4', 'mp4', None, None), + ('audio_track', 'https://a/track.wav', 'wav', None, 'speaker:0'), + ('audio_track', 'https://a/music.mp3', 'mp3', None, 'bgm:0'), + ('subtitle', 'https://a/line.srt', 'srt', 'target_srt', None), + ('subtitle', 'https://a/original.srt', 'srt', 'source_srt', None)) + + +def test_dubbing_requests_the_subtitles_it_stores(): + body = dubbing_body({'modelId': MODEL}, 'https://a/in.mp4', + {'target_language': 'en', 'source_language': 'zh'}) + assert body['include'] == ['video_url', 'subtitles.srt', 'subtitles.jsonl', + 'subtitles_source.srt', 'subtitles_source.jsonl'] + artifacts = dubbing_artifacts({'content': {'video_url': 'https://a/dubbed.mp4', 'subtitles': [ + {'format': 'srt', 'url': 'https://a/line.srt'}, {'format': 'jsonl', 'url': 'https://a/line.jsonl'}, + {'source': 'source', 'format': 'jsonl', 'url': 'https://a/plain.jsonl'}]}}) + assert artifacts[1:] == (('subtitle', 'https://a/line.srt', 'srt', 'target_srt', None), + ('subtitle', 'https://a/line.jsonl', 'jsonl', 'target_jsonl', None), + ('subtitle', 'https://a/plain.jsonl', 'jsonl', 'source_jsonl', None)) + + +@pytest.mark.anyio +async def test_a_provider_track_lands_beside_the_adopted_audio(project): + store, pid, _ = project + audio = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', + 'sine=frequency=440:sample_rate=44100', '-t', '0.3', + '-threads', '1', '-f', 'mp3', 'pipe:1'], + capture_output=True, check=True).stdout + def handler(request): + if request.method == 'GET': + return httpx.Response(200, content=audio, headers={'content-type': 'audio/mpeg'}) + return httpx.Response(200, json={'id': '0218', 'model': MODEL, + 'content': {'audios': [{'url': 'http://fixture.invalid/api/v3/mix.mp3'}, + {'url': 'http://fixture.invalid/api/v3/speaker.wav', 'type': 'speaker'}]}}) + runner, target, spec_id = setup( + project, 'audio', dict(mode='unified', creationType='audio', outputFormat='mp3', taskType='text2audio'), + handler, protocol='volcengine', model=MODEL, url=CONTENT_BASE) + + try: + _, receipt = await submit(project, runner, target, spec_id) + assert receipt.status == 'accepted', receipt + await done(runner) + snapshot = store.snapshot(pid) + finally: + await runner.close() + job = snapshot.jobs[-1] + assert job.status == 'succeeded', job.errorDetails + names = sorted(a.name for a in snapshot.assets if a.provenance.jobId == job.id) + assert names == ['Make an output-audio_track-speaker-0.wav', 'Make an output.mp3'], names + assert [r.role for r in snapshot.results if r.jobId == job.id] == ['primary', 'audio_track'] + assert [r.track for r in snapshot.results if r.jobId == job.id] == [None, 'speaker:0'] def test_dubbing_requires_a_dubbed_video_in_the_response(): From 5ff677e461a80605a7b51635aa3623a354cec36a Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:33:39 +0800 Subject: [PATCH 08/58] [feat] audio: separate a long recording into its own tracks Separation reads one recording up to six minutes and returns one entry per track, so the reference bound differs from the two-to-thirty-second voice samples a generation request takes. A separation request also carries no subtitle and no speech, loudness or pitch adjustment, which the parameters now refuse instead of forwarding to a service that ignores them. Refs #650 --- .../domain/creation/generation.py | 11 +++++++ .../src/opendirector/domain/input_rules.py | 2 +- .../src/opendirector/domain/rule_facts.py | 2 ++ .../integrations/reference_inputs.py | 14 +++++--- tests/test_seed_audio.py | 32 +++++++++++++++++-- 5 files changed, 53 insertions(+), 8 deletions(-) diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index e363794c0..17c3b7fe9 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -120,6 +120,17 @@ class AudioParameters(Contract): default=None, exclude_if=lambda value: value is None, description='Dubbing: SRT asset that fixes the spoken lines instead of listening to the video.') + @model_validator(mode='after') + def separation_shape(self): + if self.taskType != 'separation': + return self + if self.subtitleAssetId is not None: + raise ValueError('Separation takes no subtitle file') + for name in ('speechRate', 'loudnessRate', 'pitchRate'): + if getattr(self, name): + raise ValueError('Separation takes no speech, loudness or pitch adjustment') + return self + @model_validator(mode='after') def dubbing_language(self): if self.taskType == 'dubbing': diff --git a/packages/core/src/opendirector/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index 488bfd030..367259952 100644 --- a/packages/core/src/opendirector/domain/input_rules.py +++ b/packages/core/src/opendirector/domain/input_rules.py @@ -181,7 +181,7 @@ def _adapter_rules(config): if kind == 'audio' and config.get('protocol') == 'volcengine' and str(config.get('modelId') or '').startswith(SEED_AUDIO_MODEL_PREFIX): rules.update(profile='seed-audio', allowedKinds=['image', 'audio', 'video'], maxImages=1, maxAudios=6, maxVideos=1, referencesAllowed=True, maxPromptCharacters=10000, - audioTasks=['text2audio', 'dubbing'], + audioTasks=['text2audio', 'dubbing', 'separation'], outputFormats=['mp3', 'wav'], sampleRates=[8000, 16000, 24000, 32000, 44100, 48000]) return rules if kind == 'audio': diff --git a/packages/core/src/opendirector/domain/rule_facts.py b/packages/core/src/opendirector/domain/rule_facts.py index 77fc30cfb..a992ba680 100644 --- a/packages/core/src/opendirector/domain/rule_facts.py +++ b/packages/core/src/opendirector/domain/rule_facts.py @@ -16,6 +16,8 @@ SEED_AUDIO_REFERENCE_TOTAL_MS = 180000 SEED_AUDIO_DUBBING_MS = (4000, 360000) SEED_AUDIO_SUBTITLE_BYTES = 2 * 1024 * 1024 +SEED_AUDIO_SEPARATION_MS = (1000, 360000) +SEED_AUDIO_SEPARATION_TOTAL_MS = 2160000 # Storage/structure guard. Provider budgets are checked separately. MAX_REFERENCES = 64 diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 5f114eb5b..7625c495f 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -5,7 +5,7 @@ from opendirector.domain.input_rules import MAX_REFERENCES, input_rules from opendirector.domain.rule_facts import ( - CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, SEED_AUDIO_DUBBING_MS, SEED_AUDIO_REFERENCE_BYTES, SEED_AUDIO_SUBTITLE_BYTES, SEED_AUDIO_REFERENCE_MS, + CONTROL_VIDEO_SECONDS, FASTH3_MEDIA_REFERENCE_LIMIT, REFERENCE_MEDIA_SECONDS, SEED_AUDIO_DUBBING_MS, SEED_AUDIO_SEPARATION_MS, SEED_AUDIO_SEPARATION_TOTAL_MS, SEED_AUDIO_REFERENCE_BYTES, SEED_AUDIO_SUBTITLE_BYTES, SEED_AUDIO_REFERENCE_MS, SEED_AUDIO_REFERENCE_TOTAL_MS, TEXT_REFERENCE_BYTES, keyframe_frame, ) from opendirector.domain.projects import ProjectError @@ -86,7 +86,11 @@ def reference_content(store, owner, message, *, manifest=None, overrides=None): def seed_audio_references(store, task, rules, result, overrides): """Seed Audio takes one image, one video for dubbing, or voice samples, never a mix.""" total_ms = 0 - dubbing = (task.get('parameters') or {}).get('taskType') == 'dubbing' + operation = (task.get('parameters') or {}).get('taskType') + dubbing = operation == 'dubbing' + separating = operation == 'separation' + low_ms, high_ms = SEED_AUDIO_SEPARATION_MS if separating else SEED_AUDIO_REFERENCE_MS + budget_ms = SEED_AUDIO_SEPARATION_TOTAL_MS if separating else SEED_AUDIO_REFERENCE_TOTAL_MS for data, meta, source_kind in references(store, task['projectId'], task['referenceIds'], overrides): entry = {'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': source_kind, 'transmission': 'content'} if source_kind == 'image': @@ -102,12 +106,12 @@ def seed_audio_references(store, task, rules, result, overrides): if meta['type'] not in {'audio/wav', 'audio/x-wav', 'audio/mpeg'} or len(data) > SEED_AUDIO_REFERENCE_BYTES: raise ProjectError('参考音频需为不超过 15 MB 的 WAV 或 MP3。', 422, code='audio_reference_audio') duration = meta.get('durationMs') - low, high = SEED_AUDIO_REFERENCE_MS + low, high = low_ms, high_ms if duration is None or not low <= duration <= high: raise ProjectError(f'参考音频需为 {low // 1000}—{high // 1000} 秒。', 422, code='audio_reference_audio') total_ms += duration - if len(result['audios']) >= rules['maxAudios'] or total_ms > SEED_AUDIO_REFERENCE_TOTAL_MS: - raise ProjectError(f'参考音频最多 {rules["maxAudios"]} 段、合计不超过 {SEED_AUDIO_REFERENCE_TOTAL_MS // 1000} 秒。', 422, code='audio_reference_count') + if len(result['audios']) >= rules['maxAudios'] or total_ms > budget_ms: + raise ProjectError(f'参考音频最多 {rules["maxAudios"]} 段、合计不超过 {budget_ms // 1000} 秒。', 422, code='audio_reference_count') result['audios'].append(data_uri(data, 'audio/wav' if meta['type'] == 'audio/x-wav' else meta['type'])) result['manifest'].append({**entry, 'role': 'reference_audio'}) elif source_kind == 'video' and dubbing: diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index 847506860..76ebd2af7 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -50,7 +50,7 @@ def seed_model(url=CONTENT_BASE): def test_adapter_publishes_only_the_verified_operation(): rules = InputRules.model_validate(input_rules(config())) assert rules.profile == 'seed-audio' - assert rules.audioTasks == ('text2audio', 'dubbing') + assert rules.audioTasks == ('text2audio', 'dubbing', 'separation') assert rules.allowedKinds == ('image', 'audio', 'video') and rules.maxImages == 1 and rules.maxAudios == 6 assert rules.referencesAllowed is True assert rules.maxPromptCharacters == 10000 @@ -108,7 +108,7 @@ def test_unified_mode_is_accepted_only_for_the_unified_profile(): validate_generation(audio_spec(), seed_model()) for parameters, code in [({'mode': 'tts'}, 'audio_mode_required'), ({'creationType': 'music'}, 'audio_music_unsupported'), - ({'taskType': 'separation'}, 'audio_task_unsupported')]: + ({'taskType': 'reference'}, 'audio_task_unsupported')]: with pytest.raises(ProjectError) as caught: validate_generation(audio_spec(**parameters), seed_model()) assert caught.value.code == code @@ -408,3 +408,31 @@ def test_a_subtitle_that_is_not_srt_is_refused(tmp_path): with pytest.raises(ProjectError) as failure: generation_references(store, task, config()) assert failure.value.code == 'audio_subtitle_asset' + + +def test_separation_accepts_a_minute_of_audio_reference(tmp_path): + store, owner, _, voice, _ = reference_store(tmp_path) + long = {'id': str(UUID(int=70)), 'name': '访谈.wav', 'type': 'audio/wav', 'kind': 'audio', + 'fingerprint': 'fixture', 'durationMs': 120000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', long) if asset_id == long['id'] else original(project_id, asset_id) + task = store_task(owner, [long]) + task['parameters']['taskType'] = 'separation' + from opendirector.integrations.reference_inputs import generation_references + ready = generation_references(store, task, config()) + assert len(ready['audios']) == 1 + assert [entry['role'] for entry in ready['manifest']] == ['reference_audio'] + + +def test_separation_refuses_more_than_six_minutes_in_one_clip(tmp_path): + store, owner, _, _, _ = reference_store(tmp_path) + too_long = {'id': str(UUID(int=71)), 'name': '长访谈.wav', 'type': 'audio/wav', 'kind': 'audio', + 'fingerprint': 'fixture', 'durationMs': 400000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', too_long) if asset_id == too_long['id'] else original(project_id, asset_id) + task = store_task(owner, [too_long]) + task['parameters']['taskType'] = 'separation' + from opendirector.integrations.reference_inputs import generation_references + with pytest.raises(ProjectError) as failure: + generation_references(store, task, config()) + assert failure.value.code == 'audio_reference_audio' From 06e6e36d9a9f9f3827a3228555e64cc78da5ff0b Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 11:39:04 +0800 Subject: [PATCH 09/58] [feat] canvas: offer a sibling track as a node version, not a subtitle A job that produced several files registered every one of them as a result, so a node's version list showed all of them. A subtitle was listed as a version of the audio node it belonged to even though adopting it fails the media-kind check, which leaves a row the user cannot use. The list now keeps a sibling only when its media kind matches the node. A separated track still appears and can be adopted as that node's audio, which is what the delivered files are for. `result_not_adoptable` also joins the contract message catalog, so the Agent reads the reason in English instead of a Chinese sentence. Refs #650 ## tests - `tests/test_result_artifacts.py` -> 12 passed, including the new version list case that fails without the filter (`Say hello-subtitle-target_srt.srt` is offered) and passes with it - `tests/test_creation_node_versions.py test_creation_crop.py test_creation_image_edits.py test_creation_media_publication.py test_command_version_contract.py` -> 108 passed - `check:i18n` -> 3828 keys, 0 problems --- docs/architecture/unified-project.md | 2 +- .../application/creation_node_versions.py | 3 ++ .../domain/creation/contract_messages.py | 4 +++ tests/test_result_artifacts.py | 36 +++++++++++++++++++ 4 files changed, 44 insertions(+), 1 deletion(-) diff --git a/docs/architecture/unified-project.md b/docs/architecture/unified-project.md index f8b58b645..fdf47ca33 100644 --- a/docs/architecture/unified-project.md +++ b/docs/architecture/unified-project.md @@ -152,7 +152,7 @@ UI、Agent 和后台完成写入共享可恢复变更通道。通知提示对象 一次生成可以交付多个文件,例如配音后的视频、分离音轨和字幕。采用只有一个指针:`Job.asset` 与 `result.select` 只接受 `role="primary"` 的结果;其余文件属于同一任务的交付物,身份由 `(role, variant, track)` 确定,不使用供应商返回顺序编号。主结果与附加文件在同一个提交中登记,失败不会留下“主结果已在、兄弟文件丢失”的状态;中断后按恢复缓存重放同一提交,不重复登记。任务查询(`job.status` 与画布任务卡)同时返回交付文件清单,用户与 Agent 据此继续导入时间线或审片。 -One generation can deliver several files, such as a dubbed video, separated audio tracks, and subtitles. Adoption stays a single pointer: `Job.asset` and `result.select` only accept the `role="primary"` result. The other files are deliverables of the same job, identified by `(role, variant, track)` rather than by vendor response order. The adopted output and its siblings are registered in one commit, so a failure never leaves "adopted output present, sibling lost", and recovery replays the same commit instead of duplicating it. Job queries (`job.status` and canvas job cards) return the delivered artifact list, so a user or the Agent can continue into the timeline or review. +One generation can deliver several files, such as a dubbed video, separated audio tracks, and subtitles. Adoption stays a single pointer: `Job.asset` and `result.select` only accept the `role="primary"` result. The other files are deliverables of the same job, identified by `(role, variant, track)` rather than by vendor response order. The adopted output and its siblings are registered in one commit, so a failure never leaves "adopted output present, sibling lost", and recovery replays the same commit instead of duplicating it. Job queries (`job.status` and canvas job cards) return the delivered artifact list, so a user or the Agent can continue into the timeline or review. A sibling whose media kind matches the node still appears in that node's version list and can be adopted there; one that does not match, such as a subtitle on an audio node, is not offered as a version. 浏览器与后台的执行职责必须明确。Agent 可以修改时间线,不代表后台已经能够导出视频;只有存在可调用渲染服务并验证真实输出,才可声称支持关闭浏览器后的自主导出。浏览器合成也可以作为明确需要客户端参与的能力保留。 diff --git a/packages/core/src/opendirector/application/creation_node_versions.py b/packages/core/src/opendirector/application/creation_node_versions.py index 7a27ba7b8..089ea7514 100644 --- a/packages/core/src/opendirector/application/creation_node_versions.py +++ b/packages/core/src/opendirector/application/creation_node_versions.py @@ -128,6 +128,9 @@ def node_versions(projects, project_id, item_id, *, assets): evidence = family.get(asset.id) if evidence is None: continue + parent = evidence.get('result') + if parent is not None and parent.role != 'primary' and asset.kind != item.kind: + continue asset_id = asset.id available = True try: diff --git a/packages/core/src/opendirector/domain/creation/contract_messages.py b/packages/core/src/opendirector/domain/creation/contract_messages.py index c8c723508..f404fe66e 100644 --- a/packages/core/src/opendirector/domain/creation/contract_messages.py +++ b/packages/core/src/opendirector/domain/creation/contract_messages.py @@ -27,6 +27,10 @@ '内容在读取后已被修改:当前版本为 {current},提供的是 {expected}。请重新读取后再试。', 'This item changed since it was loaded: it is at revision {current}, expected {expected}. Reload it and try again.', ), + 'result_not_adoptable': ( + '附加产物(音轨、字幕)不能替代主结果采用。', + 'A side artifact (audio track or subtitle) cannot replace the adopted result.', + ), 'help_field_invalid': ( '字段路径 {requested} 无效。最近的合法路径:{nearest};{level} 层可用字段:{fields};示例:{example}', 'Invalid schema field path {requested}. Nearest valid path: {nearest}; fields at {level}: {fields}; example: {example}', diff --git a/tests/test_result_artifacts.py b/tests/test_result_artifacts.py index 5bae966b2..da8c9ce5a 100644 --- a/tests/test_result_artifacts.py +++ b/tests/test_result_artifacts.py @@ -10,6 +10,7 @@ from opendirector.application.creation_assets import CreationAssets from opendirector.application.creation_canvas import CreationCanvas +from opendirector.application.creation_history import CreationHistory from opendirector.application.creation_generation import CreationGeneration from opendirector.domain.assets import MAX_ASSET_BYTES from opendirector.domain.creation.commands import JobStatusQuery, parse_command @@ -244,3 +245,38 @@ async def test_a_subtitle_sidecar_lands_as_a_readable_text_asset(project): with stream: assert stream.read().decode() == subtitle assert (asset.kind, asset.name) == ('text', 'Use the source-subtitle-target_srt.srt') + + +class Tracks(Provider): + + async def generate_all(self, config, task, submitted, *, result_ready=None, recovery_cache=None): + self.calls.append(task) + return (GeneratedArtifact('wav', wav()), *self.extras) + + +@pytest.mark.anyio +async def test_a_track_is_offered_as_a_version_but_a_subtitle_is_not(project): + store, pid, session = project + configs = ModelConfigs(store.local.repository) + config = configs.save('audio', 'http://127.0.0.1:12345/v1', 'test-audio', '', + connection_type='self_hosted', protocol='openai', auth_mode='none') + provider = Tracks() + provider.extras = (GeneratedArtifact('wav', wav(0.3), role='audio_track', track='speaker:0'), + GeneratedArtifact('srt', b'1\n00:00:00,000 --> 00:00:01,000\nHallo\n', + role='subtitle', variant='target_srt')) + runner = CreationGeneration(store, configs, provider) + target, spec = media(project, 'audio') + changed = spec.model_copy(update={'prompt': 'Say hello', 'modelConfigId': UUID(config['id'])}) + assert send(store, pid, 'generationSpec.update', session=session, + versions=[ver('generation_spec', spec)], spec=changed).status == 'applied' + spec = store.snapshot(pid).generationSpecs[-1] + command = parse_command(dict(commandId=uuid4(), projectId=pid, type='generation.submit', + expectedVersions=[ver('generation_spec', spec), ver('canvas_item', target)], + payload=dict(specId=spec.id, expectedSpecRevision=spec.revision, originItemId=target.id, + adoptionPolicy='if_current'))) + assert (await runner.execute(command, session=session)).status == 'accepted' + await settle(runner) + assert [result.role for result in store.snapshot(pid).results] == ['primary', 'audio_track', 'subtitle'] + listing = CreationHistory(store).node_versions(pid, target.id) + assert sorted(row['asset'].name for row in listing['versions']) == [ + 'Say hello-audio_track-speaker-0.wav', 'Say hello.wav'] From dac4793b04e0655dad64728023bce7fafa949a81 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 11:41:05 +0800 Subject: [PATCH 10/58] [bugfix] api: answer the side-artifact refusal in English `result.select` rejects an audio track or subtitle with a stable `result_not_adoptable` code, but the catalog had no English text for it, so an English interface fell back to the generic status sentence. The code now carries its own English sentence, and a test pins both languages the way the neighbouring contract codes are pinned. The extended `register` docstring from the previous commit is reverted: the contract it described lives in `docs/architecture/unified-project.md` and in the tests. Refs #650 ## tests - `tests/test_localization.py` -> 9 passed - `tests/test_result_artifacts.py tests/test_agent_artifacts.py tests/test_creation_assets.py` -> 65 passed --- apps/api/src/opendirector_api/localization.py | 1 + docs/architecture/unified-project.md | 2 +- .../src/opendirector/application/creation_assets.py | 5 +---- .../core/src/opendirector/integrations/providers.py | 1 - tests/test_localization.py | 10 ++++++++++ 5 files changed, 13 insertions(+), 6 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index f8df9321d..c198291d5 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -192,6 +192,7 @@ "preview_expired": "The preview expired. Generate it again.", "reference_invalid": "A reference is no longer valid. Select it again and retry.", "role_restricted": "This item does not allow that operation.", + "result_not_adoptable": "A side artifact such as an audio track or subtitle cannot replace the adopted result. Generate again or adopt the primary output.", "canvas_run_layout_extent": "Canvas positions or dimensions are too large to arrange. Resize the affected items.", "canvas_run_layout_group": "Run layout is only available for top-level groups.", "canvas_run_layout_conflict": "Locked Run areas overlap. Unlock one of the groups and try again.", diff --git a/docs/architecture/unified-project.md b/docs/architecture/unified-project.md index fdf47ca33..14d9a18cc 100644 --- a/docs/architecture/unified-project.md +++ b/docs/architecture/unified-project.md @@ -152,7 +152,7 @@ UI、Agent 和后台完成写入共享可恢复变更通道。通知提示对象 一次生成可以交付多个文件,例如配音后的视频、分离音轨和字幕。采用只有一个指针:`Job.asset` 与 `result.select` 只接受 `role="primary"` 的结果;其余文件属于同一任务的交付物,身份由 `(role, variant, track)` 确定,不使用供应商返回顺序编号。主结果与附加文件在同一个提交中登记,失败不会留下“主结果已在、兄弟文件丢失”的状态;中断后按恢复缓存重放同一提交,不重复登记。任务查询(`job.status` 与画布任务卡)同时返回交付文件清单,用户与 Agent 据此继续导入时间线或审片。 -One generation can deliver several files, such as a dubbed video, separated audio tracks, and subtitles. Adoption stays a single pointer: `Job.asset` and `result.select` only accept the `role="primary"` result. The other files are deliverables of the same job, identified by `(role, variant, track)` rather than by vendor response order. The adopted output and its siblings are registered in one commit, so a failure never leaves "adopted output present, sibling lost", and recovery replays the same commit instead of duplicating it. Job queries (`job.status` and canvas job cards) return the delivered artifact list, so a user or the Agent can continue into the timeline or review. A sibling whose media kind matches the node still appears in that node's version list and can be adopted there; one that does not match, such as a subtitle on an audio node, is not offered as a version. +One generation can deliver several files, such as a dubbed video, separated audio tracks, and subtitles. Adoption stays a single pointer: `Job.asset` and `result.select` only accept the `role="primary"` result, which a provider always returns first. The other files are deliverables of the same job, identified by `(role, variant, track)` rather than by vendor response order. The adopted output and its siblings are registered in one commit, so a failure never leaves "adopted output present, sibling lost", and recovery replays the same commit instead of duplicating it. Job queries (`job.status` and canvas job cards) return the delivered artifact list, so a user or the Agent can continue into the timeline or review. A sibling whose media kind matches the node still appears in that node's version list and can be adopted there; one that does not match, such as a subtitle on an audio node, is not offered as a version. 浏览器与后台的执行职责必须明确。Agent 可以修改时间线,不代表后台已经能够导出视频;只有存在可调用渲染服务并验证真实输出,才可声称支持关闭浏览器后的自主导出。浏览器合成也可以作为明确需要客户端参与的能力保留。 diff --git a/packages/core/src/opendirector/application/creation_assets.py b/packages/core/src/opendirector/application/creation_assets.py index 255b9b374..2a7ada534 100644 --- a/packages/core/src/opendirector/application/creation_assets.py +++ b/packages/core/src/opendirector/application/creation_assets.py @@ -142,10 +142,7 @@ def register(self, command, *, session=None, source='ui', provenance=None, apply HTTP never accepts these extra arguments. trusted_upload selects a server-owned staged file while commit still validates the caller's editing session. Generated/edited outputs - must have real job/document evidence validated by ProjectSnapshot. staged lists further - server-owned outputs, already staged under their own handles, that belong to the same - commit: one produced file must never be registered while its siblings are lost. Those - siblings are already present in the snapshot handed to apply. + must have real job/document evidence validated by ProjectSnapshot. """ replay = self.projects.replay(command) if replay is not None: diff --git a/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index 84245b692..38a68b83a 100644 --- a/packages/core/src/opendirector/integrations/providers.py +++ b/packages/core/src/opendirector/integrations/providers.py @@ -31,7 +31,6 @@ class GeneratedArtifact(NamedTuple): - """One produced file. Index 0 of a generation result is the adopted output.""" suffix: str data: bytes diff --git a/tests/test_localization.py b/tests/test_localization.py index e96c4c824..97def31eb 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -30,6 +30,16 @@ def test_capability_messages_preserve_the_specific_input_failure(): assert localized_error(request('zh-CN'), chinese=chinese, status=422, code=code) == chinese +def test_a_side_artifact_is_refused_in_the_interface_language(): + for code, chinese, english in [ + ('result_not_adoptable', '附加产物(音轨、字幕)不能替代主结果采用。', + 'A side artifact such as an audio track or subtitle cannot replace the adopted result. ' + 'Generate again or adopt the primary output.'), + ]: + assert localized_error(request('en-US'), chinese=chinese, status=422, code=code) == english + assert localized_error(request('zh-CN'), chinese=chinese, status=422, code=code) == chinese + + def test_accept_language_uses_the_primary_language() -> None: assert wants_english(request("zh-CN,zh;q=0.9")) is False assert wants_english(request("zh-Hant")) is False From fa0b9bd40b45df056bcd0f17073751f9d6447b60 Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Fri, 4 Dec 2026 12:22:02 +0800 Subject: [PATCH 11/58] [feat] audio: explain the subtitle transport requirement before submitting A subtitle has to reach the service as a fetchable URL, and a desktop install has no public address to offer. Without storage the request now stops with `audio_subtitle_transport` instead of the generic storage message, in both interface languages. Also pins the six-track shape: one primary plus `speaker`, `sfx`, `bgm` and `composite` entries numbered within their own type. Refs #650 --- apps/api/src/opendirector_api/localization.py | 1 + .../opendirector/domain/creation/commands.py | 2 +- .../domain/creation/contract_messages.py | 4 +++ .../opendirector/integrations/volcengine.py | 3 ++ src/contracts/creation.schema.json | 2 ++ src/contracts/generated.ts | 4 +-- tests/test_seed_audio.py | 30 +++++++++++++++++++ 7 files changed, 43 insertions(+), 3 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index c198291d5..ae572be59 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -68,6 +68,7 @@ 'audio_reference_video': 'This Seed Audio adapter does not accept video references yet.', 'audio_subtitle_scope': 'A subtitle file is used only when dubbing a referenced video.', 'audio_subtitle_asset': 'The subtitle must be an SRT file within the size limit.', + 'audio_subtitle_transport': 'A subtitle file needs a fetchable address: configure object storage before dubbing with subtitles.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', 'bigmodel_video_output': 'Choose a supported CogVideoX-3 pixel size and a 5- or 10-second duration. The size determines the aspect ratio.', 'bigmodel_video_image': 'CogVideoX-3 frame images must be valid PNG or JPEG files, up to 5 MB each.', diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 680a05455..866d2f029 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -606,7 +606,7 @@ def command_fingerprint(command: Command) -> str: 'capability_unsupported', 'preview_expired', 'storage_unavailable', 'submission_unknown', 'provider_error', 'audio_music_unsupported', 'audio_mode_required', 'audio_task_unsupported', 'seed_audio_base_url', 'audio_reference_image', 'audio_reference_audio', 'audio_reference_count', 'audio_reference_mix', - 'audio_reference_video', 'audio_subtitle_scope', 'audio_subtitle_asset', 'seed_audio_storage', 'seed_audio_storage_rejected', 'seed_audio_storage_timeout', 'seed_audio_storage_unreachable', + 'audio_reference_video', 'audio_subtitle_scope', 'audio_subtitle_asset', 'audio_subtitle_transport', 'seed_audio_storage', 'seed_audio_storage_rejected', 'seed_audio_storage_timeout', 'seed_audio_storage_unreachable', 'moss_speech_text', 'moss_speech_voice', 'moss_speech_reference', 'moss_prompt_limit', 'moss_image_size', 'moss_image_reference', 'moss_layout_reference', 'bigmodel_image_size', 'bigmodel_image_reference', 'bigmodel_image_prompt', diff --git a/packages/core/src/opendirector/domain/creation/contract_messages.py b/packages/core/src/opendirector/domain/creation/contract_messages.py index f404fe66e..fdae05449 100644 --- a/packages/core/src/opendirector/domain/creation/contract_messages.py +++ b/packages/core/src/opendirector/domain/creation/contract_messages.py @@ -3,6 +3,10 @@ from pydantic_core import PydanticCustomError CONTRACT_MESSAGES = { + 'audio_subtitle_transport': ( + '字幕文件需要可拉取的地址,请先配置对象存储后再提交翻配。', + 'A subtitle file needs a fetchable address: configure object storage before dubbing with subtitles.', + ), 'version_required': ( 'expectedVersions 缺少本命令修改对象的当前版本。请读取每个对象的当前版本(query object.get --object-id ID),' '并一次全部提供:expectedVersions += [{entries}];CLI:{options}', diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index 55844a7c6..90d73147a 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -242,6 +242,9 @@ async def query(): if not prepared["videos"]: raise ProjectError("翻配需要引用一段视频。", 422, code="audio_reference_video") if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): + if prepared.get("subtitle"): + raise ProjectError("字幕文件需要可拉取的地址,请先配置对象存储后再提交翻配。", 422, + code="audio_subtitle_transport") raise ProjectError("翻配需要先配置对象存储,方舟只能拉取可访问的地址。", 422, code="seed_audio_storage") key = f"od/{task['id']}/{uuid4()}.mp4" diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 40df62ed1..3674dff32 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4786,6 +4786,7 @@ "audio_reference_video", "audio_subtitle_scope", "audio_subtitle_asset", + "audio_subtitle_transport", "seed_audio_storage", "seed_audio_storage_rejected", "seed_audio_storage_timeout", @@ -25108,6 +25109,7 @@ "audio_reference_video", "audio_subtitle_scope", "audio_subtitle_asset", + "audio_subtitle_transport", "seed_audio_storage", "seed_audio_storage_rejected", "seed_audio_storage_timeout", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 2c87584f3..feaf383cd 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -513,7 +513,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "audio_subtitle_transport" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -2573,7 +2573,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "audio_subtitle_transport" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; readonly message: string; readonly objectId: string | null; readonly field: string | null; diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index 76ebd2af7..7f2818925 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -436,3 +436,33 @@ def test_separation_refuses_more_than_six_minutes_in_one_clip(tmp_path): with pytest.raises(ProjectError) as failure: generation_references(store, task, config()) assert failure.value.code == 'audio_reference_audio' + + +def test_six_tracks_come_back_as_one_primary_and_five_tracks(): + import sys + tracks = [{'url': f'https://a/{name}.wav', 'type': name} for name in + ('speaker', 'speaker', 'sfx', 'bgm', 'composite')] + value = {'content': {'audios': [{'url': 'https://a/mix.wav'}] + tracks}} + artifacts = audio_artifacts(value) + assert artifacts[0][0] == 'primary' + assert [(a[0], a[4]) for a in artifacts[1:]] == [ + ('audio_track', 'speaker:0'), ('audio_track', 'speaker:1'), ('audio_track', 'sfx:0'), + ('audio_track', 'bgm:0'), ('audio_track', 'composite:0')] + + +def test_a_subtitle_without_storage_explains_the_transport_requirement(tmp_path): + store, owner, video = dubbing_store(tmp_path, 6000) + srt = {'id': str(UUID(int=63)), 'name': '台词.srt', 'type': 'text/plain', 'kind': 'text', + 'fingerprint': 'fixture'} + original = store.asset + store.asset = lambda project_id, asset_id: (b'1\n00:00:00,000 --> 00:00:02,000\n', srt) \ + if asset_id == srt['id'] else original(project_id, asset_id) + task = dubbing_task(owner, [video]) + task['parameters']['subtitleAssetId'] = srt['id'] + from opendirector.integrations.reference_inputs import generation_references + ready = generation_references(store, task, config()) + assert ready['subtitle'] is not None + from opendirector.domain.creation.contract_messages import CONTRACT_MESSAGES + from opendirector_api.localization import ENGLISH_BY_CODE + assert 'audio_subtitle_transport' in CONTRACT_MESSAGES + assert 'audio_subtitle_transport' in ENGLISH_BY_CODE From 3756cc8ed8da1f516eb9c48ae7cb6bbb3c7040ab Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 14:13:36 +0800 Subject: [PATCH 12/58] [bugfix] audio: send the separation intent as separate_audio MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary Seed Audio 1.5 tells 分轨 and 参考音频 apart by the `role` on each `content[].audio_url`, not by `taskType`. The outbound body hardcoded `reference_audio`, so a separation job was sent as "generate from this audio reference" and the service answered with one re-recording instead of the requested tracks; the canvas then showed one primary clip and the job read as a success. The business intent now picks the role where the request is prepared, and the outbound body only forwards what preparation decided: - `reference_inputs.seed_audio_references` records `separate_audio` for `taskType: separation` and keeps `reference_audio` for every other audio task, on the manifest entry too. - `seed_audio.request_body` takes `audio_role` and no longer hardcodes it. - `volcengine` passes the prepared role into the body. `#650` Tests: `tests/test_seed_audio.py` (39 passed), with red proof on both halves. Without the adapter pass-through the separation request goes out as `reference_audio`; without the preparation change the separation manifest raises `KeyError: 'audio_role'`. --- .../integrations/reference_inputs.py | 3 +- .../opendirector/integrations/seed_audio.py | 4 +- .../opendirector/integrations/volcengine.py | 3 +- tests/test_seed_audio.py | 41 ++++++++++++++++++- 4 files changed, 46 insertions(+), 5 deletions(-) diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index a030fc6c4..5018f3682 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -90,6 +90,7 @@ def seed_audio_references(store, task, rules, result, overrides): separating = operation == 'separation' low_ms, high_ms = SEED_AUDIO_SEPARATION_MS if separating else SEED_AUDIO_REFERENCE_MS budget_ms = SEED_AUDIO_SEPARATION_TOTAL_MS if separating else SEED_AUDIO_REFERENCE_TOTAL_MS + result['audio_role'] = 'separate_audio' if separating else 'reference_audio' for data, meta, source_kind in references(store, task['projectId'], task['referenceIds'], overrides): entry = {'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': source_kind, 'transmission': 'content'} if source_kind == 'image': @@ -112,7 +113,7 @@ def seed_audio_references(store, task, rules, result, overrides): if len(result['audios']) >= rules['maxAudios'] or total_ms > budget_ms: raise ProjectError(f'参考音频最多 {rules["maxAudios"]} 段、合计不超过 {budget_ms // 1000} 秒。', 422, code='audio_reference_count') result['audios'].append(data_uri(data, 'audio/wav' if meta['type'] == 'audio/x-wav' else meta['type'])) - result['manifest'].append({**entry, 'role': 'reference_audio'}) + result['manifest'].append({**entry, 'role': result['audio_role']}) elif source_kind == 'video' and dubbing: duration = meta.get('durationMs') low, high = SEED_AUDIO_DUBBING_MS diff --git a/packages/core/src/opendirector/integrations/seed_audio.py b/packages/core/src/opendirector/integrations/seed_audio.py index ab9847877..642b533cf 100644 --- a/packages/core/src/opendirector/integrations/seed_audio.py +++ b/packages/core/src/opendirector/integrations/seed_audio.py @@ -11,10 +11,10 @@ def is_seed_audio(model_id): return isinstance(model_id, str) and model_id.startswith(MODEL_PREFIX) -def request_body(config, prompt, parameters, images=(), audios=()): +def request_body(config, prompt, parameters, images=(), audios=(), audio_role='reference_audio'): content = [{'type': 'text', 'text': prompt}] content.extend({'type': 'image_url', 'role': 'reference_image', 'image_url': {'url': image}} for image in images) - content.extend({'type': 'audio_url', 'role': 'reference_audio', 'audio_url': {'url': audio}} for audio in audios) + content.extend({'type': 'audio_url', 'role': audio_role, 'audio_url': {'url': audio}} for audio in audios) body = {'model': config['modelId'], 'content': content, 'output_format': parameters.get('output_format') or 'mp3'} audio = {key: parameters[key] for key in diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index 55844a7c6..eb2f990a0 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -292,7 +292,8 @@ async def query(): return artifacts[0][2], await self._download(client, artifacts[0][1], secrets=secrets) if kind == "audio" and is_seed_audio(config["modelId"]): payload = seed_audio_body(config, prompt, task["parameters"], - prepared['images'], prepared['audios']) + prepared['images'], prepared['audios'], + audio_role=prepared.get('audio_role', 'reference_audio')) request_size(payload, prepared['rules']['requestBytes']) async with client.stream("POST", endpoint(config["url"], "/contents/generations"), headers=headers, json=payload) as response: diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index 76ebd2af7..96e3f70ee 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -421,7 +421,46 @@ def test_separation_accepts_a_minute_of_audio_reference(tmp_path): from opendirector.integrations.reference_inputs import generation_references ready = generation_references(store, task, config()) assert len(ready['audios']) == 1 - assert [entry['role'] for entry in ready['manifest']] == ['reference_audio'] + assert ready['audio_role'] == 'separate_audio' + assert [entry['role'] for entry in ready['manifest']] == ['separate_audio'] + + +def test_a_voice_reference_keeps_the_reference_audio_role(tmp_path): + store, owner, _, voice, _ = reference_store(tmp_path) + ready = prepared(store, owner, [voice]) + assert ready['audio_role'] == 'reference_audio' + assert request_body(config(), ready['prompt'], {'output_format': 'mp3'}, ready['images'], + ready['audios'], audio_role=ready['audio_role'])['content'][1]['role'] == 'reference_audio' + + +@pytest.mark.anyio +async def test_the_separation_job_sends_the_prepared_audio_role(monkeypatch): + from opendirector.integrations import volcengine as module + audio = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', + 'sine=frequency=440:sample_rate=44100', '-t', '0.2', + '-threads', '1', '-f', 'mp3', 'pipe:1'], + capture_output=True, check=True).stdout + posted = [] + + def handler(request): + if request.method == 'GET': + return httpx.Response(200, content=audio, headers={'content-type': 'audio/mpeg'}) + posted.append(json.loads(request.content)) + return httpx.Response(200, json={'id': '0219', 'model': MODEL, + 'content': {'audios': [{'url': 'http://fixture.invalid/api/v3/vocal.mp3', 'type': 'speaker'}]}}) + + ready = {'prompt': '分出人声与配乐。', 'images': [], 'audios': ['data:audio/wav;base64,AAAA'], + 'videos': [], 'manifest': [], 'subtitle': None, 'continueFrom': None, + 'continueSize': None, 'control': None, 'guides': [], 'audio_role': 'separate_audio', + 'rules': input_rules({**config(), 'kind': 'audio'})} + monkeypatch.setattr(module, 'generation_references', lambda store, task, configuration: ready) + provider = VolcengineGeneration(None, transport=httpx.MockTransport(handler), poll_interval=0) + task = {'kind': 'audio', 'projectId': 'p', 'prompt': '分出人声与配乐。', 'referenceIds': ['asset'], + 'parameters': {'taskType': 'separation', 'output_format': 'mp3'}} + suffix, _ = await provider.generate({**config(), 'apiKey': 'fixture-key'}, task, lambda external_id: None) + assert suffix == 'mp3' + assert posted[0]['content'][1] == {'type': 'audio_url', 'role': 'separate_audio', + 'audio_url': {'url': 'data:audio/wav;base64,AAAA'}} def test_separation_refuses_more_than_six_minutes_in_one_clip(tmp_path): From d8616a113b123fe49b51a49202cfb95d53ea98f3 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 14:17:45 +0800 Subject: [PATCH 13/58] [feat] models: keep the provider object-storage account with the account MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary Ark can only read media from an address it can fetch itself, so 翻配, 视频参考 and 按字幕配音 all need the same thing first: the source media in object storage the user owns, handed over as a signed URL. The store already reads `storage` from a resolved model configuration, but nothing wrote it, so every dubbing call died on `seed_audio_storage` before any request went out. This adds the missing owner without inventing a second place for credentials: - `ModelConfigs` keeps `storage` (`accessKey`, `secretKey`, `bucket`, `region`) on the account layer next to the API key, so one Ark service and one bucket serve every model under it. It is validated on read, hoisted into the shared service record on write, and carried across edits of any model in that account. - `storage()` answers Bucket, Region and whether the account is configured; neither secret is ever returned. `save_storage()` treats a blank field as "keep the stored value", so a settings screen never has to echo a secret back to change a bucket. - An incomplete account is refused as a whole instead of failing later inside an adapter. `#650` Tests: `tests/test_model_configs.py` (36 passed) covers sharing across one account, restart, secret masking, blank-field updates and refusal; `tests/test_seed_audio.py` (41 passed) covers dubbing going out with the presigned address, and refusing before any request when no account is configured. The credential contract is written down in `docs/architecture/unified-project.md`. --- docs/architecture/unified-project.md | 11 +++ .../infrastructure/model_configs.py | 50 +++++++++++++- tests/test_model_configs.py | 25 +++++++ tests/test_seed_audio.py | 69 +++++++++++++++++++ 4 files changed, 152 insertions(+), 3 deletions(-) diff --git a/docs/architecture/unified-project.md b/docs/architecture/unified-project.md index 14d9a18cc..03a1ffe53 100644 --- a/docs/architecture/unified-project.md +++ b/docs/architecture/unified-project.md @@ -116,6 +116,17 @@ Hiding a source display or its group does not change active references, structur 工程文件是权威数据。对象、文件、回执和变更记录通过明确的提交顺序与恢复机制协调;SQLite 可用于租约等运行协调。凭证不进入普通工程、公开回执或模型快照。 +#### 模型账号的对象存储 + +部分生成服务不接收本机文件,只能从它自己能拉取的地址读取素材。这类媒体必须先放入用户自己的对象存储,再把带签名的临时地址交给服务。凭证属于模型账号,不属于任何工程: + +- 存放在模型配置的账号层,与 API Key 同层,由该账号下的模型共享;不进入工程文件、公开回执、任务快照或执行记录。 +- 读取时只返回 Bucket、Region 和“是否已配置”,Access Key 与 Secret Key 不回传;更新时留空的字段沿用已存值。 +- 四个字段必须同时可用或同时不存在;缺失时在提交任何请求之前拒绝,并返回可本地化的错误码。 +- 交给服务的地址带有限期,同一素材在同一任务内复用同一地址,不重复上传。 + +这样翻配、视频参考和按字幕配音共用一条“先发布再生成”的路径,而不是每个适配器各自处理上传。 + UI、Agent 和后台完成写入共享可恢复变更通道。通知提示对象发生变化,查询返回权威状态;处理断线、重复和乱序,不能通过整页重载掩盖同步问题。 浏览器保存草稿、交互状态和可重建缓存。拖动中不逐指针写盘;按受影响对象更新,避免反复读取大媒体或全历史。冲突保留输入,视图保存失败与业务提交结果分别反馈。 diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index 9494704c4..43a2fc7d0 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -16,6 +16,18 @@ from opendirector.infrastructure.local_projects import child, read_json, write_json MODEL_KINDS = ("agent", "image", "video", "audio", "vision") +STORAGE_KEYS = ("accessKey", "secretKey", "bucket", "region") + + +def storage_settings(storage, *, existing=None): + """Object storage the provider account can read; blank fields keep the stored value.""" + if not isinstance(storage, dict) or set(storage) - set(STORAGE_KEYS): + raise ProjectError("对象存储设置无效,请检查 Access Key、Secret Key、Bucket 和 Region。", 409) + merged = {**(existing or {}), **{key: value.strip() for key, value in storage.items() + if isinstance(value, str) and value.strip()}} + if set(merged) != set(STORAGE_KEYS): + raise ProjectError("对象存储需要同时填写 Access Key、Secret Key、Bucket 和 Region。", 409) + return merged class ModelConfigs: @@ -40,7 +52,7 @@ def _read(self) -> list[dict]: raise ValueError() services = value.get('services', {}) if not isinstance(services, dict) or any(not {'url', 'apiKey', 'connectionType', 'authMode'} <= set(service) - or set(service) - {'url', 'apiKey', 'connectionType', 'authMode', 'capabilityAutoCheck'} for service in services.values()): + or set(service) - {'url', 'apiKey', 'connectionType', 'authMode', 'capabilityAutoCheck', 'storage'} for service in services.values()): raise ValueError() for item in value['models']: if 'providerId' in item: @@ -48,11 +60,13 @@ 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'}: + 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'}: raise ValueError() if 'capabilityAutoCheck' in item and type(item['capabilityAutoCheck']) is not bool: raise ValueError() identifier(item["id"]) + if 'storage' in item: + storage_settings(item['storage']) if item["id"] in seen or item["kind"] not in MODEL_KINDS: raise ValueError() seen.add(item["id"]) @@ -133,6 +147,8 @@ def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str item['inputModalities'] = agent_input_modalities(kind, input_modalities if input_modalities is not None else (existing or {}).get('inputModalities')) item['videoAdapter'] = video_adapter if video_adapter is not None else (existing or {}).get('videoAdapter', 'auto') raw = video_capabilities if capabilities_supplied or video_capabilities is not None else (existing or {}).get('videoCapabilities') + if existing and 'storage' in existing: + item['storage'] = existing['storage'] item['videoCapabilities'] = check_video_config(kind, connection['protocol'], item['videoAdapter'], raw) profile = input_rules(item)['profile'] if item['videoCapabilities'] is not None and profile in {'fasth3-omni', 'vllm-omni-h3'}: @@ -146,11 +162,38 @@ def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str for peer in models: if peer.get('providerId') == item['providerId']: peer.update({key: item[key] for key in ('url', 'apiKey', 'connectionType', 'authMode', 'proxyMode')}) + if 'storage' in item: + peer['storage'] = item['storage'] if auto_check is not None: peer['capabilityAutoCheck'] = auto_check self._write(models) return self._public(item) + def storage(self, config_id: str) -> dict: + """Object-storage account bound to this configuration, without its secrets.""" + with self.lock: + item = next((item for item in self._read() if item["id"] == config_id), None) + if item is None: + raise ProjectError("模型配置已被删除,请重新加载。", 404) + values = item.get("storage") or {} + return {'bucket': values.get('bucket'), 'region': values.get('region'), + 'configured': set(values) == set(STORAGE_KEYS)} + + def save_storage(self, config_id: str, storage: dict) -> dict: + """Store the account a provider such as Ark must be able to fetch media from.""" + with self.lock: + models = self._read() + existing = next((item for item in models if item["id"] == config_id), None) + if existing is None: + raise ProjectError("模型配置已被删除,请重新加载。", 404) + values = storage_settings(storage, existing=existing.get('storage')) + provider = existing.get('providerId') + for item in models: + if item is existing or (provider and item.get('providerId') == provider): + item['storage'] = dict(values) + self._write(models) + return {'bucket': values['bucket'], 'region': values['region'], 'configured': True} + def delete(self, config_id: str) -> None: with self.lock: models = self._read() @@ -165,7 +208,8 @@ def _write(self, models: list[dict]) -> None: for model in models: item = dict(model) if 'providerId' in item: - services[item['providerId']] = {key: item.pop(key) for key in ('url', 'apiKey', 'connectionType', 'authMode')} + keys = ('url', 'apiKey', 'connectionType', 'authMode') + (('storage',) if 'storage' in item else ()) + services[item['providerId']] = {key: item.pop(key) for key in keys} if 'capabilityAutoCheck' in item: services[item['providerId']]['capabilityAutoCheck'] = item.pop('capabilityAutoCheck') stored.append(item) diff --git a/tests/test_model_configs.py b/tests/test_model_configs.py index fc8d18dbb..a4602ca39 100644 --- a/tests/test_model_configs.py +++ b/tests/test_model_configs.py @@ -484,3 +484,28 @@ def test_batch_video_cards_keep_distinct_adapter_and_output_settings(api): first, second = response.json() assert first['videoCapabilities']['outputs'][0]['resolution'] == '540P' assert second['videoCapabilities'] is None and second['inputRules']['profile'] == 'vllm-omni-h3' + + +def test_object_storage_belongs_to_the_provider_account(tmp_path): + configs = ModelConfigs(tmp_path) + saved = configs.save_many('audio', 'https://ark.example/api/v3', ['doubao-seed-audio-1-5-261128', 'seed-tts-2.0'], + 'test-secret', protocol='volcengine', auth_mode='bearer') + first = saved[0]['id'] + account = {'accessKey': 'ak-probe', 'secretKey': 'sk-probe', 'bucket': 'bucket-a', 'region': 'cn-beijing'} + assert configs.storage(first) == {'bucket': None, 'region': None, 'configured': False} + assert configs.save_storage(first, account) == {'bucket': 'bucket-a', 'region': 'cn-beijing', 'configured': True} + # One Ark account means one bucket: every model of that service can fetch from it. + assert configs.resolve(saved[1]['id'], 'audio')['storage'] == account + assert 'ak-probe' not in json.dumps(configs.storage(first)) + # Editing the model keeps the account, and a restart still resolves it. + configs.save('audio', 'https://ark.example/api/v3', 'doubao-seed-audio-1-5-261128', 'new-secret', first, + protocol='volcengine', auth_mode='bearer') + assert ModelConfigs(tmp_path).resolve(first, 'audio')['storage'] == account + # A blank field keeps the stored secret; an incomplete account is refused. + assert configs.save_storage(first, {'secretKey': '', 'bucket': 'bucket-b'})['bucket'] == 'bucket-b' + assert configs.resolve(first, 'audio')['storage']['secretKey'] == 'sk-probe' + other = configs.save('image', 'https://image.example/v1', 'demo', 'test-secret') + with pytest.raises(ProjectError, match='同时填写'): + configs.save_storage(other['id'], {'bucket': 'bucket-a'}) + with pytest.raises(ProjectError, match='对象存储设置无效'): + configs.save_storage(other['id'], {'bucket': 'bucket-a', 'token': 'x'}) diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index 96e3f70ee..bd6dd7bb6 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -475,3 +475,72 @@ def test_separation_refuses_more_than_six_minutes_in_one_clip(tmp_path): with pytest.raises(ProjectError) as failure: generation_references(store, task, config()) assert failure.value.code == 'audio_reference_audio' + + +def seed_dubbing_ready(): + return {'prompt': '', 'images': [], 'audios': [], 'videos': [b'\0\0\0\x18ftypmp42'], 'manifest': [], + 'subtitle': None, 'continueFrom': None, 'continueSize': None, 'control': None, 'guides': [], + 'audio_role': 'reference_audio', 'rules': input_rules({**config(), 'kind': 'audio'})} + + +def seed_dubbing_task(): + return {'kind': 'audio', 'projectId': 'p', 'id': 'job', 'prompt': '', + 'parameters': {'taskType': 'dubbing', 'target_language': 'en', 'output_format': 'mp4'}} + + +def configured_storage(tmp_path, monkeypatch): + from opendirector.infrastructure.model_configs import ModelConfigs + from opendirector.integrations import volcengine as module + configs = ModelConfigs(tmp_path) + saved = configs.save('audio', CONTENT_BASE, MODEL, 'fixture-key', protocol='volcengine', auth_mode='bearer') + configs.save_storage(saved['id'], {'accessKey': 'ak', 'secretKey': 'sk', 'bucket': 'bucket-a', + 'region': 'cn-beijing'}) + uploaded = [] + monkeypatch.setattr(module, 'generation_references', lambda store, task, configuration: seed_dubbing_ready()) + monkeypatch.setattr(module.tos_transfer, 'put', lambda configuration, bucket, region, key, path, + access_key, secret_key, **kwargs: uploaded.append((bucket, key))) + monkeypatch.setattr(module.tos_transfer, 'presign', + lambda bucket, region, key, access_key, secret_key, expires=0: f'https://tos.example/{key}') + return configs.resolve(saved['id'], 'audio'), uploaded + + +@pytest.mark.anyio +async def test_a_configured_account_lets_the_service_fetch_the_video(tmp_path, monkeypatch): + dubbed = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', + 'sine=frequency=440:sample_rate=44100', '-t', '0.2', + '-threads', '1', '-f', 'mp3', 'pipe:1'], + capture_output=True, check=True).stdout + posted = [] + + def handler(request): + if request.method == 'GET': + return httpx.Response(200, content=dubbed, headers={'content-type': 'video/mp4'}) + posted.append(json.loads(request.content)) + return httpx.Response(200, json={'content': {'video_url': 'http://fixture.invalid/api/v3/dubbed.mp4', + 'audios': [{'url': 'http://fixture.invalid/api/v3/mix.mp3', 'type': 'composite'}]}}) + + account, uploaded = configured_storage(tmp_path, monkeypatch) + provider = VolcengineGeneration(None, transport=httpx.MockTransport(handler), poll_interval=0) + suffix, _ = await provider.generate(account, seed_dubbing_task(), lambda external_id: None) + assert suffix == 'mp4' + (bucket, key), = uploaded + assert bucket == 'bucket-a' and key.startswith('od/job/') and key.endswith('.mp4') + assert posted[0]['content'][0] == {'type': 'video_url', 'role': 'dubbing_video', + 'video_url': {'url': f'https://tos.example/{key}'}} + assert posted[0]['dubbing_config'] == {'target_language': 'en'} + + +@pytest.mark.anyio +async def test_dubbing_refuses_before_any_request_without_an_account(tmp_path, monkeypatch): + from opendirector.infrastructure.model_configs import ModelConfigs + from opendirector.integrations import volcengine as module + configs = ModelConfigs(tmp_path) + saved = configs.save('audio', CONTENT_BASE, MODEL, 'fixture-key', protocol='volcengine', auth_mode='bearer') + monkeypatch.setattr(module, 'generation_references', lambda store, task, configuration: seed_dubbing_ready()) + posted = [] + provider = VolcengineGeneration(None, transport=httpx.MockTransport( + lambda request: posted.append(request)), poll_interval=0) + with pytest.raises(ProjectError) as failure: + await provider.generate(configs.resolve(saved['id'], 'audio'), seed_dubbing_task(), lambda external_id: None) + assert failure.value.code == 'seed_audio_storage' + assert posted == [] From e82ccbb419fcef1bd7363df03ce4b85e93f9dde8 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 14:21:10 +0800 Subject: [PATCH 14/58] [feat] api: let a model service hold its object-storage credentials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary The storage account added for remote-fetch providers had no way in from outside the process, so a user could not actually configure 翻配 or 视频参考. Two endpoints on the existing model-service resource close that: `GET /api/model-services/{id}/storage` reports the bucket, region and whether the account is usable, `POST` stores the four credentials. Neither secret comes back: the response is a separate public shape with no key fields at all, and the saved account is shared by every model of the same provider service. A blank field keeps the stored value, so changing a bucket never requires re-entering the secret, and an account with only some of the four fields is refused up front. The two refusals carry stable codes (`model_storage_incomplete`, `model_storage_invalid`) registered in the contract issue codes and the English catalog, so the interface answers them in its own language instead of echoing Chinese. `#650` Tests: `tests/test_model_configs.py` (37 passed) covers the read before any account exists, saving, masking, blank-field updates, the 409 refusal in both languages and the 404 for a deleted service; `tests/test_creation_contracts.py` (82 passed) regenerates and checks the new contract shapes. --- apps/api/src/opendirector_api/localization.py | 2 + apps/api/src/opendirector_api/main.py | 10 +- apps/api/src/opendirector_api/models.py | 2 +- .../opendirector/domain/creation/commands.py | 2 +- .../opendirector/domain/creation/models.py | 13 ++ .../infrastructure/model_configs.py | 6 +- src/contracts/creation.schema.json | 168 +++++++++++++++++- src/contracts/generated.ts | 30 +++- tests/test_model_configs.py | 21 +++ 9 files changed, 245 insertions(+), 9 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index c198291d5..bcccc19d4 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -20,6 +20,8 @@ from opendirector.domain.creation.assets import ASSET_DOWNLOAD_ENGLISH ENGLISH_BY_CODE = { + 'model_storage_invalid': 'The object storage settings are not valid. Check the access key, secret key, bucket and region.', + 'model_storage_incomplete': 'Object storage needs an access key, secret key, bucket and region. Fill in all four or leave them empty.', 'video_compression_preset': 'Choose a valid compression preset.', 'video_compression_source': 'Select one video to compress.', **ASSET_DOWNLOAD_ENGLISH, diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index 1a5d95024..7a2906548 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -40,7 +40,7 @@ from opendirector_api.models import (ModelConfigInput, ModelConfigPublic, AgentModelTest, ModelCapabilityRequest, ModelDiscoveryRequest, ModelBatchInput, ToolTaskCreate, ToolPlacement, ImageSelectionCreate, AvailabilityRefresh, AvailabilityCatalog, - ModelAvailability as ModelAvailabilityResponse) + ModelAvailability as ModelAvailabilityResponse, ModelStorage, ModelStoragePublic) async def _cli_prompt_rewrite(runtime, model, thinking, messages): @@ -262,6 +262,14 @@ def get_settings(): def update_settings(value: GeneralSettingsPatch): return preferences.update(value.model_dump()) + @app.get('/api/model-services/{config_id}/storage', response_model=ModelStoragePublic) + def read_model_storage(config_id: UUID): + return model_configs.storage(str(config_id)) + + @app.post('/api/model-services/{config_id}/storage', response_model=ModelStoragePublic) + def save_model_storage(config_id: UUID, value: ModelStorage): + return model_configs.save_storage(str(config_id), value.model_dump()) + @app.delete('/api/model-services/{config_id}', status_code=204) def delete_model_service(config_id: UUID): catalog.delete_service(str(config_id)) diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index a095e33f5..3e17099e8 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -5,7 +5,7 @@ from opendirector.domain.creation.editors import ToolDraftBinding from opendirector.domain.capabilities import AgentInputModality from opendirector.domain.video_capabilities import VideoAdapter, VideoCapabilities -from opendirector.domain.creation.models import ModelAvailability, AvailabilityCatalog +from opendirector.domain.creation.models import ModelAvailability, AvailabilityCatalog, ModelStorage, ModelStoragePublic class Model(BaseModel): diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 680a05455..ea3edabc1 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -618,7 +618,7 @@ def command_fingerprint(command: Command) -> str: 'voice_not_found', 'voice_delete_unsupported', 'voice_consent_required', 'voice_name_invalid', 'voice_audio_invalid', 'voice_format', 'voice_size', 'voice_duration', 'voice_provider_protocol', 'voice_provider_error', 'voice_provider_timeout', 'voice_model_unsupported', - 'voice_name_taken', 'voice_provider_quota'] + 'voice_name_taken', 'voice_provider_quota', 'model_storage_invalid', 'model_storage_incomplete'] class ContractIssue(Contract): diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index 5146fc75d..cd2366fed 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -116,6 +116,19 @@ def consistent(self): return self +class ModelStorage(Contract): + accessKey: str = Field(default='', max_length=512, description='Object-storage access key ID; blank keeps the stored one.') + secretKey: str = Field(default='', max_length=512, description='Object-storage secret access key; blank keeps the stored one.') + bucket: str = Field(default='', max_length=200, description='Bucket the provider may read generated media from.') + region: str = Field(default='', max_length=100, description='Object-storage region of that bucket.') + + +class ModelStoragePublic(Contract): + bucket: str | None = Field(default=None, description='Stored bucket, or null when no account is configured.') + region: str | None = Field(default=None, description='Stored region, or null when no account is configured.') + configured: bool = Field(description='Whether the provider account can publish media for remote fetch.') + + class ModelConnection(Contract): kind: ModelKind = Field(description='Business object or media type.') url: str = Field(min_length=1, max_length=2048, description='Provider API base URL.') diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index 43a2fc7d0..e46b81bd7 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -22,11 +22,13 @@ def storage_settings(storage, *, existing=None): """Object storage the provider account can read; blank fields keep the stored value.""" if not isinstance(storage, dict) or set(storage) - set(STORAGE_KEYS): - raise ProjectError("对象存储设置无效,请检查 Access Key、Secret Key、Bucket 和 Region。", 409) + raise ProjectError("对象存储设置无效,请检查 Access Key、Secret Key、Bucket 和 Region。", 409, + code="model_storage_invalid") merged = {**(existing or {}), **{key: value.strip() for key, value in storage.items() if isinstance(value, str) and value.strip()}} if set(merged) != set(STORAGE_KEYS): - raise ProjectError("对象存储需要同时填写 Access Key、Secret Key、Bucket 和 Region。", 409) + raise ProjectError("对象存储需要同时填写 Access Key、Secret Key、Bucket 和 Region。", 409, + code="model_storage_incomplete") return merged diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 40df62ed1..43ff2231d 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4829,7 +4829,9 @@ "voice_provider_timeout", "voice_model_unsupported", "voice_name_taken", - "voice_provider_quota" + "voice_provider_quota", + "model_storage_invalid", + "model_storage_incomplete" ], "title": "Code", "type": "string" @@ -10978,6 +10980,82 @@ "title": "ModelSnapshot", "type": "object" }, + "ModelStorage": { + "additionalProperties": false, + "properties": { + "accessKey": { + "default": "", + "description": "Object-storage access key ID; blank keeps the stored one.", + "maxLength": 512, + "title": "Accesskey", + "type": "string" + }, + "secretKey": { + "default": "", + "description": "Object-storage secret access key; blank keeps the stored one.", + "maxLength": 512, + "title": "Secretkey", + "type": "string" + }, + "bucket": { + "default": "", + "description": "Bucket the provider may read generated media from.", + "maxLength": 200, + "title": "Bucket", + "type": "string" + }, + "region": { + "default": "", + "description": "Object-storage region of that bucket.", + "maxLength": 100, + "title": "Region", + "type": "string" + } + }, + "title": "ModelStorage", + "type": "object" + }, + "ModelStoragePublic": { + "additionalProperties": false, + "properties": { + "bucket": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored bucket, or null when no account is configured.", + "title": "Bucket" + }, + "region": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored region, or null when no account is configured.", + "title": "Region" + }, + "configured": { + "description": "Whether the provider account can publish media for remote fetch.", + "title": "Configured", + "type": "boolean" + } + }, + "required": [ + "configured" + ], + "title": "ModelStoragePublic", + "type": "object" + }, "MotionCanvasItem": { "additionalProperties": false, "properties": { @@ -25151,7 +25229,9 @@ "voice_provider_timeout", "voice_model_unsupported", "voice_name_taken", - "voice_provider_quota" + "voice_provider_quota", + "model_storage_invalid", + "model_storage_incomplete" ], "title": "Code", "type": "string" @@ -31517,6 +31597,90 @@ "title": "ModelSnapshot", "type": "object" }, + "ModelStorage": { + "additionalProperties": false, + "properties": { + "accessKey": { + "default": "", + "description": "Object-storage access key ID; blank keeps the stored one.", + "maxLength": 512, + "title": "Accesskey", + "type": "string" + }, + "secretKey": { + "default": "", + "description": "Object-storage secret access key; blank keeps the stored one.", + "maxLength": 512, + "title": "Secretkey", + "type": "string" + }, + "bucket": { + "default": "", + "description": "Bucket the provider may read generated media from.", + "maxLength": 200, + "title": "Bucket", + "type": "string" + }, + "region": { + "default": "", + "description": "Object-storage region of that bucket.", + "maxLength": 100, + "title": "Region", + "type": "string" + } + }, + "required": [ + "accessKey", + "secretKey", + "bucket", + "region" + ], + "title": "ModelStorage", + "type": "object" + }, + "ModelStoragePublic": { + "additionalProperties": false, + "properties": { + "bucket": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored bucket, or null when no account is configured.", + "title": "Bucket" + }, + "region": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored region, or null when no account is configured.", + "title": "Region" + }, + "configured": { + "description": "Whether the provider account can publish media for remote fetch.", + "title": "Configured", + "type": "boolean" + } + }, + "required": [ + "bucket", + "region", + "configured" + ], + "title": "ModelStoragePublic", + "type": "object" + }, "MotionCanvasItem": { "additionalProperties": false, "properties": { diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 2c87584f3..05ecbc556 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -513,7 +513,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -1059,6 +1059,19 @@ export interface ModelSnapshotInput extends ContractInput { readonly inputRules?: InputRulesInput | null; } +export interface ModelStorageInput extends ContractInput { + readonly accessKey?: string; + readonly secretKey?: string; + readonly bucket?: string; + readonly region?: string; +} + +export interface ModelStoragePublicInput extends ContractInput { + readonly bucket?: string | null; + readonly region?: string | null; + readonly configured: boolean; +} + export interface MotionCanvasItemInput extends EditorCanvasItemInput { readonly kind: "motion"; } @@ -2573,7 +2586,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId: string | null; readonly field: string | null; @@ -3118,6 +3131,19 @@ export interface ModelSnapshot extends Contract { readonly inputRules: InputRules | null; } +export interface ModelStorage extends Contract { + readonly accessKey: string; + readonly secretKey: string; + readonly bucket: string; + readonly region: string; +} + +export interface ModelStoragePublic extends Contract { + readonly bucket: string | null; + readonly region: string | null; + readonly configured: boolean; +} + export interface MotionCanvasItem extends EditorCanvasItem { readonly kind: "motion"; } diff --git a/tests/test_model_configs.py b/tests/test_model_configs.py index a4602ca39..4bbbb7c4c 100644 --- a/tests/test_model_configs.py +++ b/tests/test_model_configs.py @@ -509,3 +509,24 @@ def test_object_storage_belongs_to_the_provider_account(tmp_path): configs.save_storage(other['id'], {'bucket': 'bucket-a'}) with pytest.raises(ProjectError, match='对象存储设置无效'): configs.save_storage(other['id'], {'bucket': 'bucket-a', 'token': 'x'}) + + +def test_storage_settings_are_configured_through_the_api(api): + client, _ = api + created = client.post('/api/model-configs', json=payload('audio')).json() + path = f"/api/model-services/{created['id']}/storage" + assert client.get(path).json() == {'bucket': None, 'region': None, 'configured': False} + saved = client.post(path, json={'accessKey': 'ak-probe', 'secretKey': 'sk-probe', + 'bucket': 'bucket-a', 'region': 'cn-beijing'}) + assert saved.status_code == 200 + assert saved.json() == {'bucket': 'bucket-a', 'region': 'cn-beijing', 'configured': True} + assert 'sk-probe' not in saved.text and 'ak-probe' not in saved.text + assert client.get(path).json()['configured'] is True + assert client.post(path, json={'bucket': ''}).json()['bucket'] == 'bucket-a' + fresh = client.post('/api/model-configs', json=payload('image')).json() + refused = client.post(f"/api/model-services/{fresh['id']}/storage", json={'bucket': 'bucket-a'}) + assert refused.status_code == 409 and refused.json()['code'] == 'model_storage_incomplete' + english = client.post(f"/api/model-services/{fresh['id']}/storage", json={'bucket': 'bucket-a'}, + headers={'accept-language': 'en-US'}) + assert english.json()['detail'].startswith('Object storage needs an access key') + assert client.post(f"/api/model-services/{uuid4()}/storage", json={}).status_code == 404 From e687722ddf96858f14cfbb66a59d0b37b33d6841 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:13:35 +0800 Subject: [PATCH 15/58] [refactor] audio: publish provider media through one helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary Ark can only read what it can fetch itself, so every request that carries a file has to put it in the user's bucket first and hand over a signed address. Dubbing did that inline for its video and, once subtitles arrived, a second nearly identical block grew inside the same branch — two copies of put, presign, cleanup and error mapping that the reference and subtitle paths would each have had to repeat. `_publish_media(config, task_id, data, suffix, content_type, noun=...)` now owns that step: it refuses before writing anything when the account is unconfigured, writes the bytes to a temporary file, uploads, presigns for an hour and always removes the temp file. Dubbing calls it for the video and for the subtitle, so the behaviour is the one already covered by the existing dubbing and subtitle tests, not a new one. The noun stays a parameter so a failure still says which file could not be published; the error code keeps coming from the transfer so the interface can answer in its own language. `#650` Tests: `tests/test_seed_audio.py` + `tests/test_result_artifacts.py` 53 passed, including the dubbing body carrying the presigned video URL and the subtitle travelling with it. --- .../opendirector/integrations/volcengine.py | 60 ++++++++----------- 1 file changed, 25 insertions(+), 35 deletions(-) diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index eb2f990a0..35950f656 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -238,45 +238,14 @@ async def query(): raise protocol_failure(stage) await asyncio.sleep(self.poll_interval) if kind == "audio" and is_seed_audio(config["modelId"]) and task["parameters"].get("taskType") == "dubbing": - storage = config.get("storage") or {} if not prepared["videos"]: raise ProjectError("翻配需要引用一段视频。", 422, code="audio_reference_video") - if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): - raise ProjectError("翻配需要先配置对象存储,方舟只能拉取可访问的地址。", 422, - code="seed_audio_storage") - key = f"od/{task['id']}/{uuid4()}.mp4" - media = prepared["videos"][0] - path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.mp4") - with open(path, "wb") as handle: - handle.write(media) - try: - await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], - key, path, storage["accessKey"], storage["secretKey"], - content_type="video/mp4") - except tos_transfer.TransferError as error: - raise ProjectError("视频上传失败,请检查对象存储配置后重试。", 502, - code=f"seed_audio_{error.code}") from error - finally: - os.unlink(path) - source = tos_transfer.presign(storage["bucket"], storage["region"], key, - storage["accessKey"], storage["secretKey"], expires=3600) + source = await self._publish_media(config, task["id"], prepared["videos"][0], "mp4", "video/mp4", + noun="视频") subtitle_url = None if prepared.get("subtitle"): - subtitle_key = f"od/{task['id']}/{uuid4()}.srt" - subtitle_path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.srt") - with open(subtitle_path, "wb") as handle: - handle.write(prepared["subtitle"]) - try: - await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], - subtitle_key, subtitle_path, storage["accessKey"], - storage["secretKey"], content_type="application/x-subrip") - except tos_transfer.TransferError as error: - raise ProjectError("字幕上传失败,请检查对象存储配置后重试。", 502, - code=f"seed_audio_{error.code}") from error - finally: - os.unlink(subtitle_path) - subtitle_url = tos_transfer.presign(storage["bucket"], storage["region"], subtitle_key, - storage["accessKey"], storage["secretKey"], expires=3600) + subtitle_url = await self._publish_media(config, task["id"], prepared["subtitle"], "srt", + "application/x-subrip", noun="字幕") payload = seed_audio_dubbing_body(config, source, task["parameters"], subtitle_url) stage = 'submit' async with client.stream("POST", endpoint(config["url"], "/contents/generations"), @@ -337,6 +306,27 @@ async def query(): except (ValueError, TypeError, KeyError, IndexError, AttributeError): raise protocol_failure(stage) from None + async def _publish_media(self, config, task_id, data, suffix, content_type, *, noun="素材"): + """Put one file where the provider can fetch it and return an address it may read.""" + storage = config.get("storage") or {} + if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): + raise ProjectError("该任务需要先配置对象存储,方舟只能拉取可访问的地址。", 422, + code="seed_audio_storage") + key = f"od/{task_id}/{uuid4()}.{suffix}" + path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.{suffix}") + with open(path, "wb") as handle: + handle.write(data) + try: + await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], key, path, + storage["accessKey"], storage["secretKey"], content_type=content_type) + except tos_transfer.TransferError as error: + raise ProjectError(f"{noun}上传失败,请检查对象存储配置后重试。", 502, + code=f"seed_audio_{error.code}") from error + finally: + os.unlink(path) + return tos_transfer.presign(storage["bucket"], storage["region"], key, + storage["accessKey"], storage["secretKey"], expires=3600) + async def _download(self, client, url, *, secrets=(), public_only=False): parts = urlsplit(url) if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username or parts.password: From bc9842fac9c18933134799b7dceb7018740fe3fe Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:16:09 +0800 Subject: [PATCH 16/58] [refactor] audio: decide storage readiness in one place ## summary Two call sites now need the same yes/no answer about the provider account: the upload helper itself, and the subtitle path, which has to tell "this job has a subtitle and nothing to publish it with" apart from a plain missing account before it calls the helper. Keeping the four-field test in both places would let them drift, and a drifting readiness check shows up as a wrong error code rather than a test failure. `_storage_ready(config)` holds it once and `_publish_media` asks it, so the subtitle path and the helper can never disagree about whether the same account is usable. It stays on the Ark adapter: object storage is a property of a provider that only reads remote URLs, not of every generation provider, and the base class has no other reason to know about buckets. `#650` Tests: `tests/test_seed_audio.py` + `tests/test_result_artifacts.py` 53 passed, including dubbing refused with `seed_audio_storage` before any request when no account is configured, and publishing the video and subtitle when one is. --- .../core/src/opendirector/integrations/volcengine.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index 35950f656..ec7cfdd91 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -306,12 +306,17 @@ async def query(): except (ValueError, TypeError, KeyError, IndexError, AttributeError): raise protocol_failure(stage) from None + def _storage_ready(self, config): + """Whether this account can publish media for a provider that only reads remote URLs.""" + storage = config.get("storage") or {} + return all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")) + async def _publish_media(self, config, task_id, data, suffix, content_type, *, noun="素材"): """Put one file where the provider can fetch it and return an address it may read.""" - storage = config.get("storage") or {} - if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): + if not self._storage_ready(config): raise ProjectError("该任务需要先配置对象存储,方舟只能拉取可访问的地址。", 422, code="seed_audio_storage") + storage = config["storage"] key = f"od/{task_id}/{uuid4()}.{suffix}" path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.{suffix}") with open(path, "wb") as handle: From 372504f2700853d1d52c0f3d170a79ac04527efc Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:30:57 +0800 Subject: [PATCH 17/58] [feat] assets: upload a subtitle file as a subtitle asset MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary 按字幕配音 needs an uploaded SRT, but the upload inspector only recognised `.txt` and `.md` as text. An `.srt` fell through to the media branch and came back as a generic file, so no subtitle asset could ever exist and `subtitleAssetId` was unreachable from the interface — the validation in the audio reference layer was correct and simply could never be satisfied. `.srt` now inspects as text with `application/x-subrip`, which is the type the reference layer already accepts. The size and UTF-8 checks are the existing text ones; a subtitle that is not valid SRT timings is still refused later, by the rule that owns that judgement. `#650` Tests: `tests/test_creation_assets.py::test_an_srt_upload_becomes_a_subtitle_asset` uploads a real SRT through the API and reads the bytes back; `tests/test_seed_audio.py` now asserts the reference layer accepts both `text/plain` and `application/x-subrip` subtitles. That test failed with `kind == 'file'` before `.srt` was recognised. 235 passed across the seven modules touched by this branch. --- .../src/opendirector/infrastructure/creation_uploads.py | 5 +++-- tests/test_creation_assets.py | 8 ++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/core/src/opendirector/infrastructure/creation_uploads.py b/packages/core/src/opendirector/infrastructure/creation_uploads.py index eead9a10f..88c34ab5e 100644 --- a/packages/core/src/opendirector/infrastructure/creation_uploads.py +++ b/packages/core/src/opendirector/infrastructure/creation_uploads.py @@ -59,7 +59,7 @@ def inspect_file(path: Path, name: str, *, expected_kind=None): if suffix in {'.ttf', '.otf', '.ttc', '.otc', '.woff', '.woff2'} or prefix[:4] in FONT_SIGNATURES: font = inspect_font(path) return 'file', MediaMetadata(size=size, mimeType=font.mimeType) - if suffix in {'.txt', '.md'} or expected_kind == 'text': + if suffix in {'.txt', '.md', '.srt'} or expected_kind == 'text': if size > MAX_CREATION_TEXT_BYTES: raise ProjectError('文本素材应不超过 1 MiB。', 413) try: @@ -68,7 +68,8 @@ def inspect_file(path: Path, name: str, *, expected_kind=None): raise ProjectError('文本素材需使用 UTF-8 编码。') from None if any(ord(char) < 32 and char not in '\t\r\n' for char in text): raise ProjectError('文件包含非文本内容,请导入 UTF-8 文本。') - return 'text', MediaMetadata(size=size, mimeType='text/markdown' if suffix == '.md' else 'text/plain') + mime = {'md': 'text/markdown', 'srt': 'application/x-subrip'}.get(suffix.lstrip('.'), 'text/plain') + return 'text', MediaMetadata(size=size, mimeType=mime) with path.open('rb') as stream: prefix = stream.read(16) image_bytes = (prefix.startswith((b'\x89PNG\r\n\x1a\n', b'\xff\xd8\xff', b'GIF87a', b'GIF89a')) diff --git a/tests/test_creation_assets.py b/tests/test_creation_assets.py index 03228966e..013cc5707 100644 --- a/tests/test_creation_assets.py +++ b/tests/test_creation_assets.py @@ -579,6 +579,14 @@ def test_empty_text_and_generic_files_have_safe_content_access(api): assert response.headers['content-disposition'].startswith('attachment;') +def test_an_srt_upload_becomes_a_subtitle_asset(api): + client, base, _, project_id = api + lines = '1\n00:00:00,000 --> 00:00:02,000\n你好\n\n'.encode() + info, _, asset_id = api_upload(client, base, data=lines, name='lines.srt') + assert info['kind'] == 'text' and info['metadata']['mimeType'] == 'application/x-subrip' + assert client.get(base + '/assets/' + asset_id + '/content').content == lines + + def test_clipboard_image_without_suffix_is_inspected_from_its_bytes(api): client, base, _, _ = api info, _, asset_id = api_upload(client, base, name='clipboard') From 539d96081974a49b54b1d61d4a4bc67739e73c9f Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:33:13 +0800 Subject: [PATCH 18/58] [feat] audio: accept the four reference shapes Seed Audio allows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary The provider takes exactly four reference combinations: one image, one video, up to six voice clips, or one video with voice clips. The adapter only ever implemented the first and third. A video fell into the "not supported" branch unless the task was dubbing, and voice clips were refused next to a video, so 视频参考生音频 and 音视频参考生音频 could not be requested at all — both are in the acceptance list for `#650`. Video is now a reference like any other. Dubbing keeps its own role `dubbing_video` and its MP4-only bound; every other task sends `reference_video` and accepts MP4 or MOV. Because the service can only fetch video from a URL, a reference video goes through the same `_publish_media` path as the dubbing source, and the declared content type follows the container brand instead of assuming MP4. The mix rule now states the real constraint: image cannot be combined with video or voice, and dubbing cannot carry voice clips. Image plus voice stays refused, as before. Three codes were added so each refusal keeps its own meaning in both languages: `audio_dubbing_video` (wrong format or length for dubbing), `audio_dubbing_source` (no source video), `audio_separation_video` (separation takes audio only). `audio_reference_video` now only means a video the service cannot accept, and `audio_reference_count` and `audio_reference_mix` were reworded to describe the wider matrix. `#650` Tests: `tests/test_seed_audio.py` covers a video travelling as `reference_video`, a video with a voice clip travelling together, the image-plus-video and separation-plus-video refusals, the declared type for both container brands, and a published video arriving in the request body. The publish test fails with an empty publish list before the adapter change. `tests/test_localization.py` answers each new code in English and Chinese. 236 passed across the seven modules touched by this branch. --- apps/api/src/opendirector_api/localization.py | 9 +- .../opendirector/domain/creation/commands.py | 2 +- .../integrations/reference_inputs.py | 25 +++-- .../opendirector/integrations/seed_audio.py | 8 +- .../opendirector/integrations/volcengine.py | 13 ++- src/contracts/creation.schema.json | 6 ++ src/contracts/generated.ts | 4 +- tests/test_localization.py | 15 +++ tests/test_seed_audio.py | 101 ++++++++++++++++-- 9 files changed, 157 insertions(+), 26 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index bcccc19d4..4a2c55321 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -65,9 +65,12 @@ 'seed_audio_base_url': 'Seed Audio 1.5 needs the Ark content-generation base URL ending in /api/v3. Add the Seed Audio preset instead.', 'audio_reference_image': 'That reference cannot be sent: Seed Audio takes PNG, JPEG or WEBP images within the size limit.', 'audio_reference_audio': 'Voice references must be WAV or MP3 and 2 to 30 seconds long.', - 'audio_reference_count': 'Seed Audio takes at most one image or six voice references, up to 180 seconds in total.', - 'audio_reference_mix': 'Seed Audio cannot combine an image reference with voice references.', - 'audio_reference_video': 'This Seed Audio adapter does not accept video references yet.', + 'audio_reference_count': 'Seed Audio takes at most one image, one video, or six voice references up to 180 seconds in total.', + 'audio_reference_mix': 'Seed Audio cannot combine these inputs: send one image, one video with optional voice clips, or voice clips alone.', + 'audio_reference_video': 'A video reference must be MP4 or MOV, 4 seconds to 6 minutes.', + 'audio_dubbing_video': 'A dubbing source must be an MP4 clip of 4 seconds to 6 minutes.', + 'audio_dubbing_source': 'Dubbing needs a source video to re-voice.', + 'audio_separation_video': 'Track separation takes one audio input and no video.', 'audio_subtitle_scope': 'A subtitle file is used only when dubbing a referenced video.', 'audio_subtitle_asset': 'The subtitle must be an SRT file within the size limit.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index ea3edabc1..f2f8d1910 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -606,7 +606,7 @@ def command_fingerprint(command: Command) -> str: 'capability_unsupported', 'preview_expired', 'storage_unavailable', 'submission_unknown', 'provider_error', 'audio_music_unsupported', 'audio_mode_required', 'audio_task_unsupported', 'seed_audio_base_url', 'audio_reference_image', 'audio_reference_audio', 'audio_reference_count', 'audio_reference_mix', - 'audio_reference_video', 'audio_subtitle_scope', 'audio_subtitle_asset', 'seed_audio_storage', 'seed_audio_storage_rejected', 'seed_audio_storage_timeout', 'seed_audio_storage_unreachable', + 'audio_reference_video', 'audio_dubbing_video', 'audio_dubbing_source', 'audio_separation_video', 'audio_subtitle_scope', 'audio_subtitle_asset', 'seed_audio_storage', 'seed_audio_storage_rejected', 'seed_audio_storage_timeout', 'seed_audio_storage_unreachable', 'moss_speech_text', 'moss_speech_voice', 'moss_speech_reference', 'moss_prompt_limit', 'moss_image_size', 'moss_image_reference', 'moss_layout_reference', 'bigmodel_image_size', 'bigmodel_image_reference', 'bigmodel_image_prompt', diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 5018f3682..4d76bf8b2 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -114,17 +114,22 @@ def seed_audio_references(store, task, rules, result, overrides): raise ProjectError(f'参考音频最多 {rules["maxAudios"]} 段、合计不超过 {budget_ms // 1000} 秒。', 422, code='audio_reference_count') result['audios'].append(data_uri(data, 'audio/wav' if meta['type'] == 'audio/x-wav' else meta['type'])) result['manifest'].append({**entry, 'role': result['audio_role']}) - elif source_kind == 'video' and dubbing: + elif source_kind == 'video': + if separating: + raise ProjectError('分轨只接收一段音频,不支持视频。', 422, code='audio_separation_video') duration = meta.get('durationMs') low, high = SEED_AUDIO_DUBBING_MS - if meta.get('type') not in {'video/mp4'} or duration is None or not low <= duration <= high: - raise ProjectError('翻配视频需为 MP4,时长 4 秒至 6 分钟。', 422, code='audio_reference_video') - if result['videos']: - raise ProjectError('翻配一次只能引用一段视频。', 422, code='audio_reference_count') + accepted = {'video/mp4'} if dubbing else {'video/mp4', 'video/quicktime'} + if meta.get('type') not in accepted or duration is None or not low <= duration <= high: + if dubbing: + raise ProjectError('翻配视频需为 MP4,时长 4 秒至 6 分钟。', 422, code='audio_dubbing_video') + raise ProjectError('参考视频需为 MP4 或 MOV,时长 4 秒至 6 分钟。', 422, code='audio_reference_video') + if len(result['videos']) >= rules['maxVideos']: + raise ProjectError('Seed Audio 1.5 一次只能引用一段视频。', 422, code='audio_reference_count') result['videos'].append(data) - result['manifest'].append({**entry, 'role': 'dubbing_video'}) + result['manifest'].append({**entry, 'role': 'dubbing_video' if dubbing else 'reference_video'}) else: - raise ProjectError(f'“{meta["name"]}”:Seed Audio 1.5 暂不接受视频参考。', 422, code='audio_reference_video') + raise ProjectError(f'“{meta["name"]}”:Seed Audio 1.5 不接受这个素材。', 422, code='audio_reference_mix') subtitle_id = (task.get('parameters') or {}).get('subtitleAssetId') if subtitle_id: if not dubbing or not result['videos']: @@ -137,8 +142,10 @@ def seed_audio_references(store, task, rules, result, overrides): result['subtitle'] = data result['manifest'].append({'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': 'text', 'transmission': 'content', 'role': 'custom_subtitle'}) - if result['videos'] and (result['images'] or result['audios']): - raise ProjectError('翻配视频不能与图片或音频参考同时使用。', 422, code='audio_reference_mix') + if result['videos'] and result['images']: + raise ProjectError('Seed Audio 1.5 的视频参考与图片参考不能同时使用。', 422, code='audio_reference_mix') + if dubbing and result['audios']: + raise ProjectError('翻配视频不能再搭配音频参考,请改用普通音频参考生成。', 422, code='audio_reference_mix') if result['images'] and result['audios']: raise ProjectError('Seed Audio 1.5 的图片参考与音频参考不能同时使用。', 422, code='audio_reference_mix') return result diff --git a/packages/core/src/opendirector/integrations/seed_audio.py b/packages/core/src/opendirector/integrations/seed_audio.py index 642b533cf..a6fb76151 100644 --- a/packages/core/src/opendirector/integrations/seed_audio.py +++ b/packages/core/src/opendirector/integrations/seed_audio.py @@ -11,10 +11,11 @@ def is_seed_audio(model_id): return isinstance(model_id, str) and model_id.startswith(MODEL_PREFIX) -def request_body(config, prompt, parameters, images=(), audios=(), audio_role='reference_audio'): +def request_body(config, prompt, parameters, images=(), audios=(), audio_role='reference_audio', videos=()): content = [{'type': 'text', 'text': prompt}] content.extend({'type': 'image_url', 'role': 'reference_image', 'image_url': {'url': image}} for image in images) content.extend({'type': 'audio_url', 'role': audio_role, 'audio_url': {'url': audio}} for audio in audios) + content.extend({'type': 'video_url', 'role': 'reference_video', 'video_url': {'url': video}} for video in videos) body = {'model': config['modelId'], 'content': content, 'output_format': parameters.get('output_format') or 'mp3'} audio = {key: parameters[key] for key in @@ -40,6 +41,11 @@ def dubbing_body(config, video_url, parameters, subtitle_url=None): return body +def video_type(data): + brand = data[8:12] if data[4:8] == b'ftyp' else b'' + return 'video/quicktime' if brand in {b'qt ', b'qt'} else 'video/mp4' + + def artifact_suffix(url, allowed, default): suffix = urlsplit(url).path.rsplit('.', 1)[-1].lower() return suffix if suffix in allowed else default diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index ec7cfdd91..2421b41a1 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -20,7 +20,7 @@ from opendirector.integrations.generation_errors import checked, protocol_failure, provider_failure, transport_failure from opendirector.integrations.seed_audio import (audio_artifacts as seed_audio_artifacts, is_seed_audio, dubbing_artifacts as seed_audio_dubbing_artifacts, dubbing_body as seed_audio_dubbing_body, - request_body as seed_audio_body) + request_body as seed_audio_body, video_type as seed_audio_video_type) from opendirector.integrations import tos_transfer from opendirector.media.probe import require_ffprobe @@ -239,7 +239,7 @@ async def query(): await asyncio.sleep(self.poll_interval) if kind == "audio" and is_seed_audio(config["modelId"]) and task["parameters"].get("taskType") == "dubbing": if not prepared["videos"]: - raise ProjectError("翻配需要引用一段视频。", 422, code="audio_reference_video") + raise ProjectError("翻配需要引用一段视频。", 422, code="audio_dubbing_source") source = await self._publish_media(config, task["id"], prepared["videos"][0], "mp4", "video/mp4", noun="视频") subtitle_url = None @@ -260,9 +260,16 @@ async def query(): await extra_ready(role, variant, track, extra_suffix, url) return artifacts[0][2], await self._download(client, artifacts[0][1], secrets=secrets) if kind == "audio" and is_seed_audio(config["modelId"]): + videos = [] + for data in prepared['videos']: + content_type = seed_audio_video_type(data) + videos.append(await self._publish_media( + config, task["id"], data, "mov" if content_type == "video/quicktime" else "mp4", + content_type, noun="视频")) payload = seed_audio_body(config, prompt, task["parameters"], prepared['images'], prepared['audios'], - audio_role=prepared.get('audio_role', 'reference_audio')) + audio_role=prepared.get('audio_role', 'reference_audio'), + videos=videos) request_size(payload, prepared['rules']['requestBytes']) async with client.stream("POST", endpoint(config["url"], "/contents/generations"), headers=headers, json=payload) as response: diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 43ff2231d..b1b6427b7 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4784,6 +4784,9 @@ "audio_reference_count", "audio_reference_mix", "audio_reference_video", + "audio_dubbing_video", + "audio_dubbing_source", + "audio_separation_video", "audio_subtitle_scope", "audio_subtitle_asset", "seed_audio_storage", @@ -25184,6 +25187,9 @@ "audio_reference_count", "audio_reference_mix", "audio_reference_video", + "audio_dubbing_video", + "audio_dubbing_source", + "audio_separation_video", "audio_subtitle_scope", "audio_subtitle_asset", "seed_audio_storage", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 05ecbc556..8e9c9ceb8 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -513,7 +513,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_dubbing_video" | "audio_dubbing_source" | "audio_separation_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -2586,7 +2586,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_dubbing_video" | "audio_dubbing_source" | "audio_separation_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId: string | null; readonly field: string | null; diff --git a/tests/test_localization.py b/tests/test_localization.py index 97def31eb..cf0ffd624 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -40,6 +40,21 @@ def test_a_side_artifact_is_refused_in_the_interface_language(): assert localized_error(request('zh-CN'), chinese=chinese, status=422, code=code) == chinese +def test_a_video_reference_is_refused_in_the_interface_language(): + for code, chinese, english in [ + ('audio_reference_video', '参考视频需为 MP4 或 MOV,时长 4 秒至 6 分钟。', + 'A video reference must be MP4 or MOV, 4 seconds to 6 minutes.'), + ('audio_dubbing_video', '翻配视频需为 MP4,时长 4 秒至 6 分钟。', + 'A dubbing source must be an MP4 clip of 4 seconds to 6 minutes.'), + ('audio_dubbing_source', '翻配需要引用一段视频。', + 'Dubbing needs a source video to re-voice.'), + ('audio_separation_video', '分轨只接收一段音频,不支持视频。', + 'Track separation takes one audio input and no video.'), + ]: + assert localized_error(request('en-US'), chinese=chinese, status=422, code=code) == english + assert localized_error(request('zh-CN'), chinese=chinese, status=422, code=code) == chinese + + def test_accept_language_uses_the_primary_language() -> None: assert wants_english(request("zh-CN,zh;q=0.9")) is False assert wants_english(request("zh-Hant")) is False diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index bd6dd7bb6..acdf91342 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -16,7 +16,7 @@ from opendirector.domain.input_rules import input_rules from opendirector.domain.projects import ProjectError from opendirector.integrations.seed_audio import (audio_artifacts, dubbing_artifacts, dubbing_body, - request_body) + request_body, video_type) from opendirector.integrations.volcengine import VolcengineGeneration from test_creation_contracts import entity, model as public_model from test_creation_canvas_service import project # noqa: F401 (pytest fixture) @@ -232,15 +232,55 @@ def test_voice_references_must_be_two_to_thirty_seconds(tmp_path): assert failure.value.code == 'audio_reference_audio' -def test_video_references_stay_unsupported(tmp_path): +def test_a_video_reference_travels_as_a_reference_video(tmp_path, monkeypatch): store, owner, _, _, _ = reference_store(tmp_path) video = {'id': str(UUID(int=40)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', 'fingerprint': 'fixture', 'durationMs': 5000} original = store.asset store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + ready = prepared(store, owner, [video]) + assert len(ready['videos']) == 1 and ready['audios'] == [] and ready['images'] == [] + assert [entry['role'] for entry in ready['manifest']] == ['reference_video'] + body = request_body(config(), ready['prompt'], {'output_format': 'mp3'}, ready['images'], + ready['audios'], videos=['https://storage.example/od/clip.mp4']) + assert body['content'][-1] == {'type': 'video_url', 'role': 'reference_video', + 'video_url': {'url': 'https://storage.example/od/clip.mp4'}} + + +def test_a_video_and_a_voice_reference_travel_together(tmp_path): + store, owner, _, voice, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=41)), 'name': '片段.mov', 'type': 'video/quicktime', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': 8000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + ready = prepared(store, owner, [video, voice]) + assert len(ready['videos']) == 1 and len(ready['audios']) == 1 + assert [entry['role'] for entry in ready['manifest']] == ['reference_video', 'reference_audio'] + + +def test_a_video_reference_cannot_be_mixed_with_an_image(tmp_path): + store, owner, image, _, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=42)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': 5000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + with pytest.raises(ProjectError) as failure: + prepared(store, owner, [image, video]) + assert failure.value.code == 'audio_reference_mix' + + +def test_separation_takes_no_video(tmp_path): + store, owner, _, _, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=43)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': 5000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + task = store_task(owner, [video]) + task['parameters']['taskType'] = 'separation' + from opendirector.integrations.reference_inputs import generation_references with pytest.raises(ProjectError) as failure: - prepared(store, owner, [video]) - assert failure.value.code == 'audio_reference_video' + generation_references(store, task, config()) + assert failure.value.code == 'audio_separation_video' def dubbing_task(owner, refs, **parameters): @@ -345,7 +385,7 @@ def test_dubbing_rejects_a_video_outside_the_accepted_duration(tmp_path): store, owner, video = dubbing_store(tmp_path, 3000) with pytest.raises(ProjectError) as failure: dubbing_ready(store, owner, [video]) - assert failure.value.code == 'audio_reference_video' + assert failure.value.code == 'audio_dubbing_video' def test_dubbing_cannot_mix_a_video_with_voice_samples(tmp_path): @@ -368,9 +408,10 @@ def test_dubbing_carries_a_custom_subtitle_url(tmp_path): assert ready['subtitle'] is None -def test_a_subtitle_asset_travels_with_the_dubbed_video(tmp_path): +@pytest.mark.parametrize('mime', ['text/plain', 'application/x-subrip']) +def test_a_subtitle_asset_travels_with_the_dubbed_video(tmp_path, mime): store, owner, video = dubbing_store(tmp_path, 6000) - srt = {'id': str(UUID(int=60)), 'name': '台词.srt', 'type': 'text/plain', 'kind': 'text', + srt = {'id': str(UUID(int=60)), 'name': '台词.srt', 'type': mime, 'kind': 'text', 'fingerprint': 'fixture'} original = store.asset body = b'1\n00:00:00,000 --> 00:00:02,000\n\n' @@ -463,6 +504,52 @@ def handler(request): 'audio_url': {'url': 'data:audio/wav;base64,AAAA'}} +def test_the_declared_video_type_follows_the_container_brand(): + assert video_type(b'\x00\x00\x00\x18ftypmp42') == 'video/mp4' + assert video_type(b'\x00\x00\x00\x14ftypqt ') == 'video/quicktime' + + +@pytest.mark.anyio +async def test_a_video_reference_is_published_before_the_request(monkeypatch): + from opendirector.integrations import volcengine as module + audio = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', + 'sine=frequency=440:sample_rate=44100', '-t', '0.2', + '-threads', '1', '-f', 'mp3', 'pipe:1'], + capture_output=True, check=True).stdout + posted = [] + + def handler(request): + if request.method == 'GET': + return httpx.Response(200, content=audio, headers={'content-type': 'audio/mpeg'}) + posted.append(json.loads(request.content)) + return httpx.Response(200, json={'id': '0219', 'model': MODEL, + 'content': {'audios': [{'url': 'http://fixture.invalid/api/v3/mix.mp3'}]}}) + + clip = b'\x00\x00\x00\x18ftypmp42' + ready = {'prompt': '跟着画面配一段动效声。', 'images': [], 'audios': ['data:audio/wav;base64,AAAA'], + 'videos': [clip], 'manifest': [], 'subtitle': None, 'continueFrom': None, + 'continueSize': None, 'control': None, 'guides': [], 'audio_role': 'reference_audio', + 'rules': input_rules({**config(), 'kind': 'audio'})} + monkeypatch.setattr(module, 'generation_references', lambda store, task, configuration: ready) + published = [] + + async def publish(configuration, task_id, data, suffix, content_type, *, noun='素材'): + published.append((data, suffix, content_type, noun)) + return 'https://storage.example/od/clip.mp4' + + monkeypatch.setattr(VolcengineGeneration, '_publish_media', staticmethod(publish)) + provider = VolcengineGeneration(None, transport=httpx.MockTransport(handler), poll_interval=0) + task = {'id': 'job', 'kind': 'audio', 'projectId': 'p', 'prompt': '跟着画面配一段动效声。', + 'referenceIds': ['asset'], 'parameters': {'taskType': 'reference', 'output_format': 'mp3'}} + suffix, _ = await provider.generate({**config(), 'apiKey': 'fixture-key'}, task, lambda external_id: None) + assert suffix == 'mp3' + assert published == [(clip, 'mp4', 'video/mp4', '视频')] + assert posted[0]['content'][-1] == {'type': 'video_url', 'role': 'reference_video', + 'video_url': {'url': 'https://storage.example/od/clip.mp4'}} + assert posted[0]['content'][1] == {'type': 'audio_url', 'role': 'reference_audio', + 'audio_url': {'url': 'data:audio/wav;base64,AAAA'}} + + def test_separation_refuses_more_than_six_minutes_in_one_clip(tmp_path): store, owner, _, _, _ = reference_store(tmp_path) too_long = {'id': str(UUID(int=71)), 'name': '长访谈.wav', 'type': 'audio/wav', 'kind': 'audio', From 8680d8c219d806b5e56d5bd46c06c6f11c14ba3c Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Fri, 4 Dec 2026 15:39:53 +0800 Subject: [PATCH 19/58] [fix] api: keep the subtitle transport message in one catalog Audio issue codes reach the interface through `ENGLISH_BY_CODE` only, so the duplicate entry in `CONTRACT_MESSAGES` carried a translation nothing reads. Refs #650 --- .../src/opendirector/domain/creation/contract_messages.py | 4 ---- tests/test_seed_audio.py | 2 -- 2 files changed, 6 deletions(-) diff --git a/packages/core/src/opendirector/domain/creation/contract_messages.py b/packages/core/src/opendirector/domain/creation/contract_messages.py index fdae05449..f404fe66e 100644 --- a/packages/core/src/opendirector/domain/creation/contract_messages.py +++ b/packages/core/src/opendirector/domain/creation/contract_messages.py @@ -3,10 +3,6 @@ from pydantic_core import PydanticCustomError CONTRACT_MESSAGES = { - 'audio_subtitle_transport': ( - '字幕文件需要可拉取的地址,请先配置对象存储后再提交翻配。', - 'A subtitle file needs a fetchable address: configure object storage before dubbing with subtitles.', - ), 'version_required': ( 'expectedVersions 缺少本命令修改对象的当前版本。请读取每个对象的当前版本(query object.get --object-id ID),' '并一次全部提供:expectedVersions += [{entries}];CLI:{options}', diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index 0e3c020db..f4479451d 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -588,9 +588,7 @@ def test_a_subtitle_without_storage_explains_the_transport_requirement(tmp_path) from opendirector.integrations.reference_inputs import generation_references ready = generation_references(store, task, config()) assert ready['subtitle'] is not None - from opendirector.domain.creation.contract_messages import CONTRACT_MESSAGES from opendirector_api.localization import ENGLISH_BY_CODE - assert 'audio_subtitle_transport' in CONTRACT_MESSAGES assert 'audio_subtitle_transport' in ENGLISH_BY_CODE def seed_dubbing_ready(): return {'prompt': '', 'images': [], 'audios': [], 'videos': [b'\0\0\0\x18ftypmp42'], 'manifest': [], From 41c01b4475f1953cbfee74d46f3dbf07b7d34166 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 14:17:45 +0800 Subject: [PATCH 20/58] [feat] models: keep the provider object-storage account with the account MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary Ark can only read media from an address it can fetch itself, so 翻配, 视频参考 and 按字幕配音 all need the same thing first: the source media in object storage the user owns, handed over as a signed URL. The store already reads `storage` from a resolved model configuration, but nothing wrote it, so every dubbing call died on `seed_audio_storage` before any request went out. This adds the missing owner without inventing a second place for credentials: - `ModelConfigs` keeps `storage` (`accessKey`, `secretKey`, `bucket`, `region`) on the account layer next to the API key, so one Ark service and one bucket serve every model under it. It is validated on read, hoisted into the shared service record on write, and carried across edits of any model in that account. - `storage()` answers Bucket, Region and whether the account is configured; neither secret is ever returned. `save_storage()` treats a blank field as "keep the stored value", so a settings screen never has to echo a secret back to change a bucket. - An incomplete account is refused as a whole instead of failing later inside an adapter. `#650` Tests: `tests/test_model_configs.py` (36 passed) covers sharing across one account, restart, secret masking, blank-field updates and refusal; `tests/test_seed_audio.py` (41 passed) covers dubbing going out with the presigned address, and refusing before any request when no account is configured. The credential contract is written down in `docs/architecture/unified-project.md`. --- docs/architecture/unified-project.md | 11 +++ .../infrastructure/model_configs.py | 50 +++++++++++++- tests/test_model_configs.py | 22 ++++++ tests/test_seed_audio.py | 69 +++++++++++++++++++ 4 files changed, 149 insertions(+), 3 deletions(-) diff --git a/docs/architecture/unified-project.md b/docs/architecture/unified-project.md index 14d9a18cc..03a1ffe53 100644 --- a/docs/architecture/unified-project.md +++ b/docs/architecture/unified-project.md @@ -116,6 +116,17 @@ Hiding a source display or its group does not change active references, structur 工程文件是权威数据。对象、文件、回执和变更记录通过明确的提交顺序与恢复机制协调;SQLite 可用于租约等运行协调。凭证不进入普通工程、公开回执或模型快照。 +#### 模型账号的对象存储 + +部分生成服务不接收本机文件,只能从它自己能拉取的地址读取素材。这类媒体必须先放入用户自己的对象存储,再把带签名的临时地址交给服务。凭证属于模型账号,不属于任何工程: + +- 存放在模型配置的账号层,与 API Key 同层,由该账号下的模型共享;不进入工程文件、公开回执、任务快照或执行记录。 +- 读取时只返回 Bucket、Region 和“是否已配置”,Access Key 与 Secret Key 不回传;更新时留空的字段沿用已存值。 +- 四个字段必须同时可用或同时不存在;缺失时在提交任何请求之前拒绝,并返回可本地化的错误码。 +- 交给服务的地址带有限期,同一素材在同一任务内复用同一地址,不重复上传。 + +这样翻配、视频参考和按字幕配音共用一条“先发布再生成”的路径,而不是每个适配器各自处理上传。 + UI、Agent 和后台完成写入共享可恢复变更通道。通知提示对象发生变化,查询返回权威状态;处理断线、重复和乱序,不能通过整页重载掩盖同步问题。 浏览器保存草稿、交互状态和可重建缓存。拖动中不逐指针写盘;按受影响对象更新,避免反复读取大媒体或全历史。冲突保留输入,视图保存失败与业务提交结果分别反馈。 diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index 9494704c4..43a2fc7d0 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -16,6 +16,18 @@ from opendirector.infrastructure.local_projects import child, read_json, write_json MODEL_KINDS = ("agent", "image", "video", "audio", "vision") +STORAGE_KEYS = ("accessKey", "secretKey", "bucket", "region") + + +def storage_settings(storage, *, existing=None): + """Object storage the provider account can read; blank fields keep the stored value.""" + if not isinstance(storage, dict) or set(storage) - set(STORAGE_KEYS): + raise ProjectError("对象存储设置无效,请检查 Access Key、Secret Key、Bucket 和 Region。", 409) + merged = {**(existing or {}), **{key: value.strip() for key, value in storage.items() + if isinstance(value, str) and value.strip()}} + if set(merged) != set(STORAGE_KEYS): + raise ProjectError("对象存储需要同时填写 Access Key、Secret Key、Bucket 和 Region。", 409) + return merged class ModelConfigs: @@ -40,7 +52,7 @@ def _read(self) -> list[dict]: raise ValueError() services = value.get('services', {}) if not isinstance(services, dict) or any(not {'url', 'apiKey', 'connectionType', 'authMode'} <= set(service) - or set(service) - {'url', 'apiKey', 'connectionType', 'authMode', 'capabilityAutoCheck'} for service in services.values()): + or set(service) - {'url', 'apiKey', 'connectionType', 'authMode', 'capabilityAutoCheck', 'storage'} for service in services.values()): raise ValueError() for item in value['models']: if 'providerId' in item: @@ -48,11 +60,13 @@ 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'}: + 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'}: raise ValueError() if 'capabilityAutoCheck' in item and type(item['capabilityAutoCheck']) is not bool: raise ValueError() identifier(item["id"]) + if 'storage' in item: + storage_settings(item['storage']) if item["id"] in seen or item["kind"] not in MODEL_KINDS: raise ValueError() seen.add(item["id"]) @@ -133,6 +147,8 @@ def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str item['inputModalities'] = agent_input_modalities(kind, input_modalities if input_modalities is not None else (existing or {}).get('inputModalities')) item['videoAdapter'] = video_adapter if video_adapter is not None else (existing or {}).get('videoAdapter', 'auto') raw = video_capabilities if capabilities_supplied or video_capabilities is not None else (existing or {}).get('videoCapabilities') + if existing and 'storage' in existing: + item['storage'] = existing['storage'] item['videoCapabilities'] = check_video_config(kind, connection['protocol'], item['videoAdapter'], raw) profile = input_rules(item)['profile'] if item['videoCapabilities'] is not None and profile in {'fasth3-omni', 'vllm-omni-h3'}: @@ -146,11 +162,38 @@ def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str for peer in models: if peer.get('providerId') == item['providerId']: peer.update({key: item[key] for key in ('url', 'apiKey', 'connectionType', 'authMode', 'proxyMode')}) + if 'storage' in item: + peer['storage'] = item['storage'] if auto_check is not None: peer['capabilityAutoCheck'] = auto_check self._write(models) return self._public(item) + def storage(self, config_id: str) -> dict: + """Object-storage account bound to this configuration, without its secrets.""" + with self.lock: + item = next((item for item in self._read() if item["id"] == config_id), None) + if item is None: + raise ProjectError("模型配置已被删除,请重新加载。", 404) + values = item.get("storage") or {} + return {'bucket': values.get('bucket'), 'region': values.get('region'), + 'configured': set(values) == set(STORAGE_KEYS)} + + def save_storage(self, config_id: str, storage: dict) -> dict: + """Store the account a provider such as Ark must be able to fetch media from.""" + with self.lock: + models = self._read() + existing = next((item for item in models if item["id"] == config_id), None) + if existing is None: + raise ProjectError("模型配置已被删除,请重新加载。", 404) + values = storage_settings(storage, existing=existing.get('storage')) + provider = existing.get('providerId') + for item in models: + if item is existing or (provider and item.get('providerId') == provider): + item['storage'] = dict(values) + self._write(models) + return {'bucket': values['bucket'], 'region': values['region'], 'configured': True} + def delete(self, config_id: str) -> None: with self.lock: models = self._read() @@ -165,7 +208,8 @@ def _write(self, models: list[dict]) -> None: for model in models: item = dict(model) if 'providerId' in item: - services[item['providerId']] = {key: item.pop(key) for key in ('url', 'apiKey', 'connectionType', 'authMode')} + keys = ('url', 'apiKey', 'connectionType', 'authMode') + (('storage',) if 'storage' in item else ()) + services[item['providerId']] = {key: item.pop(key) for key in keys} if 'capabilityAutoCheck' in item: services[item['providerId']]['capabilityAutoCheck'] = item.pop('capabilityAutoCheck') stored.append(item) diff --git a/tests/test_model_configs.py b/tests/test_model_configs.py index fc8d18dbb..5a6dc345e 100644 --- a/tests/test_model_configs.py +++ b/tests/test_model_configs.py @@ -484,3 +484,25 @@ def test_batch_video_cards_keep_distinct_adapter_and_output_settings(api): first, second = response.json() assert first['videoCapabilities']['outputs'][0]['resolution'] == '540P' assert second['videoCapabilities'] is None and second['inputRules']['profile'] == 'vllm-omni-h3' + + +def test_object_storage_belongs_to_the_provider_account(tmp_path): + configs = ModelConfigs(tmp_path) + saved = configs.save_many('audio', 'https://ark.example/api/v3', ['doubao-seed-audio-1-5-261128', 'seed-tts-2.0'], + 'test-secret', protocol='volcengine', auth_mode='bearer') + first = saved[0]['id'] + account = {'accessKey': 'ak-probe', 'secretKey': 'sk-probe', 'bucket': 'bucket-a', 'region': 'cn-beijing'} + assert configs.storage(first) == {'bucket': None, 'region': None, 'configured': False} + assert configs.save_storage(first, account) == {'bucket': 'bucket-a', 'region': 'cn-beijing', 'configured': True} + assert configs.resolve(saved[1]['id'], 'audio')['storage'] == account + assert 'ak-probe' not in json.dumps(configs.storage(first)) + configs.save('audio', 'https://ark.example/api/v3', 'doubao-seed-audio-1-5-261128', 'new-secret', first, + protocol='volcengine', auth_mode='bearer') + assert ModelConfigs(tmp_path).resolve(first, 'audio')['storage'] == account + assert configs.save_storage(first, {'secretKey': '', 'bucket': 'bucket-b'})['bucket'] == 'bucket-b' + assert configs.resolve(first, 'audio')['storage']['secretKey'] == 'sk-probe' + other = configs.save('image', 'https://image.example/v1', 'demo', 'test-secret') + with pytest.raises(ProjectError, match='同时填写'): + configs.save_storage(other['id'], {'bucket': 'bucket-a'}) + with pytest.raises(ProjectError, match='对象存储设置无效'): + configs.save_storage(other['id'], {'bucket': 'bucket-a', 'token': 'x'}) diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index 96e3f70ee..bd6dd7bb6 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -475,3 +475,72 @@ def test_separation_refuses_more_than_six_minutes_in_one_clip(tmp_path): with pytest.raises(ProjectError) as failure: generation_references(store, task, config()) assert failure.value.code == 'audio_reference_audio' + + +def seed_dubbing_ready(): + return {'prompt': '', 'images': [], 'audios': [], 'videos': [b'\0\0\0\x18ftypmp42'], 'manifest': [], + 'subtitle': None, 'continueFrom': None, 'continueSize': None, 'control': None, 'guides': [], + 'audio_role': 'reference_audio', 'rules': input_rules({**config(), 'kind': 'audio'})} + + +def seed_dubbing_task(): + return {'kind': 'audio', 'projectId': 'p', 'id': 'job', 'prompt': '', + 'parameters': {'taskType': 'dubbing', 'target_language': 'en', 'output_format': 'mp4'}} + + +def configured_storage(tmp_path, monkeypatch): + from opendirector.infrastructure.model_configs import ModelConfigs + from opendirector.integrations import volcengine as module + configs = ModelConfigs(tmp_path) + saved = configs.save('audio', CONTENT_BASE, MODEL, 'fixture-key', protocol='volcengine', auth_mode='bearer') + configs.save_storage(saved['id'], {'accessKey': 'ak', 'secretKey': 'sk', 'bucket': 'bucket-a', + 'region': 'cn-beijing'}) + uploaded = [] + monkeypatch.setattr(module, 'generation_references', lambda store, task, configuration: seed_dubbing_ready()) + monkeypatch.setattr(module.tos_transfer, 'put', lambda configuration, bucket, region, key, path, + access_key, secret_key, **kwargs: uploaded.append((bucket, key))) + monkeypatch.setattr(module.tos_transfer, 'presign', + lambda bucket, region, key, access_key, secret_key, expires=0: f'https://tos.example/{key}') + return configs.resolve(saved['id'], 'audio'), uploaded + + +@pytest.mark.anyio +async def test_a_configured_account_lets_the_service_fetch_the_video(tmp_path, monkeypatch): + dubbed = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', + 'sine=frequency=440:sample_rate=44100', '-t', '0.2', + '-threads', '1', '-f', 'mp3', 'pipe:1'], + capture_output=True, check=True).stdout + posted = [] + + def handler(request): + if request.method == 'GET': + return httpx.Response(200, content=dubbed, headers={'content-type': 'video/mp4'}) + posted.append(json.loads(request.content)) + return httpx.Response(200, json={'content': {'video_url': 'http://fixture.invalid/api/v3/dubbed.mp4', + 'audios': [{'url': 'http://fixture.invalid/api/v3/mix.mp3', 'type': 'composite'}]}}) + + account, uploaded = configured_storage(tmp_path, monkeypatch) + provider = VolcengineGeneration(None, transport=httpx.MockTransport(handler), poll_interval=0) + suffix, _ = await provider.generate(account, seed_dubbing_task(), lambda external_id: None) + assert suffix == 'mp4' + (bucket, key), = uploaded + assert bucket == 'bucket-a' and key.startswith('od/job/') and key.endswith('.mp4') + assert posted[0]['content'][0] == {'type': 'video_url', 'role': 'dubbing_video', + 'video_url': {'url': f'https://tos.example/{key}'}} + assert posted[0]['dubbing_config'] == {'target_language': 'en'} + + +@pytest.mark.anyio +async def test_dubbing_refuses_before_any_request_without_an_account(tmp_path, monkeypatch): + from opendirector.infrastructure.model_configs import ModelConfigs + from opendirector.integrations import volcengine as module + configs = ModelConfigs(tmp_path) + saved = configs.save('audio', CONTENT_BASE, MODEL, 'fixture-key', protocol='volcengine', auth_mode='bearer') + monkeypatch.setattr(module, 'generation_references', lambda store, task, configuration: seed_dubbing_ready()) + posted = [] + provider = VolcengineGeneration(None, transport=httpx.MockTransport( + lambda request: posted.append(request)), poll_interval=0) + with pytest.raises(ProjectError) as failure: + await provider.generate(configs.resolve(saved['id'], 'audio'), seed_dubbing_task(), lambda external_id: None) + assert failure.value.code == 'seed_audio_storage' + assert posted == [] From fad8a5ece758d170d7c6282cdbeda3bf66922f58 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 14:21:10 +0800 Subject: [PATCH 21/58] [feat] api: let a model service hold its object-storage credentials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary The storage account added for remote-fetch providers had no way in from outside the process, so a user could not actually configure 翻配 or 视频参考. Two endpoints on the existing model-service resource close that: `GET /api/model-services/{id}/storage` reports the bucket, region and whether the account is usable, `POST` stores the four credentials. Neither secret comes back: the response is a separate public shape with no key fields at all, and the saved account is shared by every model of the same provider service. A blank field keeps the stored value, so changing a bucket never requires re-entering the secret, and an account with only some of the four fields is refused up front. The two refusals carry stable codes (`model_storage_incomplete`, `model_storage_invalid`) registered in the contract issue codes and the English catalog, so the interface answers them in its own language instead of echoing Chinese. `#650` Tests: `tests/test_model_configs.py` (37 passed) covers the read before any account exists, saving, masking, blank-field updates, the 409 refusal in both languages and the 404 for a deleted service; `tests/test_creation_contracts.py` (82 passed) regenerates and checks the new contract shapes. --- apps/api/src/opendirector_api/localization.py | 2 + apps/api/src/opendirector_api/main.py | 10 +- apps/api/src/opendirector_api/models.py | 2 +- .../opendirector/domain/creation/commands.py | 2 +- .../opendirector/domain/creation/models.py | 13 ++ .../infrastructure/model_configs.py | 6 +- src/contracts/creation.schema.json | 168 +++++++++++++++++- src/contracts/generated.ts | 30 +++- tests/test_model_configs.py | 21 +++ 9 files changed, 245 insertions(+), 9 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index c198291d5..bcccc19d4 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -20,6 +20,8 @@ from opendirector.domain.creation.assets import ASSET_DOWNLOAD_ENGLISH ENGLISH_BY_CODE = { + 'model_storage_invalid': 'The object storage settings are not valid. Check the access key, secret key, bucket and region.', + 'model_storage_incomplete': 'Object storage needs an access key, secret key, bucket and region. Fill in all four or leave them empty.', 'video_compression_preset': 'Choose a valid compression preset.', 'video_compression_source': 'Select one video to compress.', **ASSET_DOWNLOAD_ENGLISH, diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index 1a5d95024..7a2906548 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -40,7 +40,7 @@ from opendirector_api.models import (ModelConfigInput, ModelConfigPublic, AgentModelTest, ModelCapabilityRequest, ModelDiscoveryRequest, ModelBatchInput, ToolTaskCreate, ToolPlacement, ImageSelectionCreate, AvailabilityRefresh, AvailabilityCatalog, - ModelAvailability as ModelAvailabilityResponse) + ModelAvailability as ModelAvailabilityResponse, ModelStorage, ModelStoragePublic) async def _cli_prompt_rewrite(runtime, model, thinking, messages): @@ -262,6 +262,14 @@ def get_settings(): def update_settings(value: GeneralSettingsPatch): return preferences.update(value.model_dump()) + @app.get('/api/model-services/{config_id}/storage', response_model=ModelStoragePublic) + def read_model_storage(config_id: UUID): + return model_configs.storage(str(config_id)) + + @app.post('/api/model-services/{config_id}/storage', response_model=ModelStoragePublic) + def save_model_storage(config_id: UUID, value: ModelStorage): + return model_configs.save_storage(str(config_id), value.model_dump()) + @app.delete('/api/model-services/{config_id}', status_code=204) def delete_model_service(config_id: UUID): catalog.delete_service(str(config_id)) diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index a095e33f5..3e17099e8 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -5,7 +5,7 @@ from opendirector.domain.creation.editors import ToolDraftBinding from opendirector.domain.capabilities import AgentInputModality from opendirector.domain.video_capabilities import VideoAdapter, VideoCapabilities -from opendirector.domain.creation.models import ModelAvailability, AvailabilityCatalog +from opendirector.domain.creation.models import ModelAvailability, AvailabilityCatalog, ModelStorage, ModelStoragePublic class Model(BaseModel): diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 680a05455..ea3edabc1 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -618,7 +618,7 @@ def command_fingerprint(command: Command) -> str: 'voice_not_found', 'voice_delete_unsupported', 'voice_consent_required', 'voice_name_invalid', 'voice_audio_invalid', 'voice_format', 'voice_size', 'voice_duration', 'voice_provider_protocol', 'voice_provider_error', 'voice_provider_timeout', 'voice_model_unsupported', - 'voice_name_taken', 'voice_provider_quota'] + 'voice_name_taken', 'voice_provider_quota', 'model_storage_invalid', 'model_storage_incomplete'] class ContractIssue(Contract): diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index 5146fc75d..cd2366fed 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -116,6 +116,19 @@ def consistent(self): return self +class ModelStorage(Contract): + accessKey: str = Field(default='', max_length=512, description='Object-storage access key ID; blank keeps the stored one.') + secretKey: str = Field(default='', max_length=512, description='Object-storage secret access key; blank keeps the stored one.') + bucket: str = Field(default='', max_length=200, description='Bucket the provider may read generated media from.') + region: str = Field(default='', max_length=100, description='Object-storage region of that bucket.') + + +class ModelStoragePublic(Contract): + bucket: str | None = Field(default=None, description='Stored bucket, or null when no account is configured.') + region: str | None = Field(default=None, description='Stored region, or null when no account is configured.') + configured: bool = Field(description='Whether the provider account can publish media for remote fetch.') + + class ModelConnection(Contract): kind: ModelKind = Field(description='Business object or media type.') url: str = Field(min_length=1, max_length=2048, description='Provider API base URL.') diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index 43a2fc7d0..e46b81bd7 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -22,11 +22,13 @@ def storage_settings(storage, *, existing=None): """Object storage the provider account can read; blank fields keep the stored value.""" if not isinstance(storage, dict) or set(storage) - set(STORAGE_KEYS): - raise ProjectError("对象存储设置无效,请检查 Access Key、Secret Key、Bucket 和 Region。", 409) + raise ProjectError("对象存储设置无效,请检查 Access Key、Secret Key、Bucket 和 Region。", 409, + code="model_storage_invalid") merged = {**(existing or {}), **{key: value.strip() for key, value in storage.items() if isinstance(value, str) and value.strip()}} if set(merged) != set(STORAGE_KEYS): - raise ProjectError("对象存储需要同时填写 Access Key、Secret Key、Bucket 和 Region。", 409) + raise ProjectError("对象存储需要同时填写 Access Key、Secret Key、Bucket 和 Region。", 409, + code="model_storage_incomplete") return merged diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 40df62ed1..43ff2231d 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4829,7 +4829,9 @@ "voice_provider_timeout", "voice_model_unsupported", "voice_name_taken", - "voice_provider_quota" + "voice_provider_quota", + "model_storage_invalid", + "model_storage_incomplete" ], "title": "Code", "type": "string" @@ -10978,6 +10980,82 @@ "title": "ModelSnapshot", "type": "object" }, + "ModelStorage": { + "additionalProperties": false, + "properties": { + "accessKey": { + "default": "", + "description": "Object-storage access key ID; blank keeps the stored one.", + "maxLength": 512, + "title": "Accesskey", + "type": "string" + }, + "secretKey": { + "default": "", + "description": "Object-storage secret access key; blank keeps the stored one.", + "maxLength": 512, + "title": "Secretkey", + "type": "string" + }, + "bucket": { + "default": "", + "description": "Bucket the provider may read generated media from.", + "maxLength": 200, + "title": "Bucket", + "type": "string" + }, + "region": { + "default": "", + "description": "Object-storage region of that bucket.", + "maxLength": 100, + "title": "Region", + "type": "string" + } + }, + "title": "ModelStorage", + "type": "object" + }, + "ModelStoragePublic": { + "additionalProperties": false, + "properties": { + "bucket": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored bucket, or null when no account is configured.", + "title": "Bucket" + }, + "region": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored region, or null when no account is configured.", + "title": "Region" + }, + "configured": { + "description": "Whether the provider account can publish media for remote fetch.", + "title": "Configured", + "type": "boolean" + } + }, + "required": [ + "configured" + ], + "title": "ModelStoragePublic", + "type": "object" + }, "MotionCanvasItem": { "additionalProperties": false, "properties": { @@ -25151,7 +25229,9 @@ "voice_provider_timeout", "voice_model_unsupported", "voice_name_taken", - "voice_provider_quota" + "voice_provider_quota", + "model_storage_invalid", + "model_storage_incomplete" ], "title": "Code", "type": "string" @@ -31517,6 +31597,90 @@ "title": "ModelSnapshot", "type": "object" }, + "ModelStorage": { + "additionalProperties": false, + "properties": { + "accessKey": { + "default": "", + "description": "Object-storage access key ID; blank keeps the stored one.", + "maxLength": 512, + "title": "Accesskey", + "type": "string" + }, + "secretKey": { + "default": "", + "description": "Object-storage secret access key; blank keeps the stored one.", + "maxLength": 512, + "title": "Secretkey", + "type": "string" + }, + "bucket": { + "default": "", + "description": "Bucket the provider may read generated media from.", + "maxLength": 200, + "title": "Bucket", + "type": "string" + }, + "region": { + "default": "", + "description": "Object-storage region of that bucket.", + "maxLength": 100, + "title": "Region", + "type": "string" + } + }, + "required": [ + "accessKey", + "secretKey", + "bucket", + "region" + ], + "title": "ModelStorage", + "type": "object" + }, + "ModelStoragePublic": { + "additionalProperties": false, + "properties": { + "bucket": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored bucket, or null when no account is configured.", + "title": "Bucket" + }, + "region": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored region, or null when no account is configured.", + "title": "Region" + }, + "configured": { + "description": "Whether the provider account can publish media for remote fetch.", + "title": "Configured", + "type": "boolean" + } + }, + "required": [ + "bucket", + "region", + "configured" + ], + "title": "ModelStoragePublic", + "type": "object" + }, "MotionCanvasItem": { "additionalProperties": false, "properties": { diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 2c87584f3..05ecbc556 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -513,7 +513,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -1059,6 +1059,19 @@ export interface ModelSnapshotInput extends ContractInput { readonly inputRules?: InputRulesInput | null; } +export interface ModelStorageInput extends ContractInput { + readonly accessKey?: string; + readonly secretKey?: string; + readonly bucket?: string; + readonly region?: string; +} + +export interface ModelStoragePublicInput extends ContractInput { + readonly bucket?: string | null; + readonly region?: string | null; + readonly configured: boolean; +} + export interface MotionCanvasItemInput extends EditorCanvasItemInput { readonly kind: "motion"; } @@ -2573,7 +2586,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId: string | null; readonly field: string | null; @@ -3118,6 +3131,19 @@ export interface ModelSnapshot extends Contract { readonly inputRules: InputRules | null; } +export interface ModelStorage extends Contract { + readonly accessKey: string; + readonly secretKey: string; + readonly bucket: string; + readonly region: string; +} + +export interface ModelStoragePublic extends Contract { + readonly bucket: string | null; + readonly region: string | null; + readonly configured: boolean; +} + export interface MotionCanvasItem extends EditorCanvasItem { readonly kind: "motion"; } diff --git a/tests/test_model_configs.py b/tests/test_model_configs.py index 5a6dc345e..cdefff969 100644 --- a/tests/test_model_configs.py +++ b/tests/test_model_configs.py @@ -506,3 +506,24 @@ def test_object_storage_belongs_to_the_provider_account(tmp_path): configs.save_storage(other['id'], {'bucket': 'bucket-a'}) with pytest.raises(ProjectError, match='对象存储设置无效'): configs.save_storage(other['id'], {'bucket': 'bucket-a', 'token': 'x'}) + + +def test_storage_settings_are_configured_through_the_api(api): + client, _ = api + created = client.post('/api/model-configs', json=payload('audio')).json() + path = f"/api/model-services/{created['id']}/storage" + assert client.get(path).json() == {'bucket': None, 'region': None, 'configured': False} + saved = client.post(path, json={'accessKey': 'ak-probe', 'secretKey': 'sk-probe', + 'bucket': 'bucket-a', 'region': 'cn-beijing'}) + assert saved.status_code == 200 + assert saved.json() == {'bucket': 'bucket-a', 'region': 'cn-beijing', 'configured': True} + assert 'sk-probe' not in saved.text and 'ak-probe' not in saved.text + assert client.get(path).json()['configured'] is True + assert client.post(path, json={'bucket': ''}).json()['bucket'] == 'bucket-a' + fresh = client.post('/api/model-configs', json=payload('image')).json() + refused = client.post(f"/api/model-services/{fresh['id']}/storage", json={'bucket': 'bucket-a'}) + assert refused.status_code == 409 and refused.json()['code'] == 'model_storage_incomplete' + english = client.post(f"/api/model-services/{fresh['id']}/storage", json={'bucket': 'bucket-a'}, + headers={'accept-language': 'en-US'}) + assert english.json()['detail'].startswith('Object storage needs an access key') + assert client.post(f"/api/model-services/{uuid4()}/storage", json={}).status_code == 404 From f80709d93c43385278aa70f079c6361e79f03062 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:13:35 +0800 Subject: [PATCH 22/58] [refactor] audio: publish provider media through one helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary Ark can only read what it can fetch itself, so every request that carries a file has to put it in the user's bucket first and hand over a signed address. Dubbing did that inline for its video and, once subtitles arrived, a second nearly identical block grew inside the same branch — two copies of put, presign, cleanup and error mapping that the reference and subtitle paths would each have had to repeat. `_publish_media(config, task_id, data, suffix, content_type, noun=...)` now owns that step: it refuses before writing anything when the account is unconfigured, writes the bytes to a temporary file, uploads, presigns for an hour and always removes the temp file. Dubbing calls it for the video and for the subtitle, so the behaviour is the one already covered by the existing dubbing and subtitle tests, not a new one. The noun stays a parameter so a failure still says which file could not be published; the error code keeps coming from the transfer so the interface can answer in its own language. `#650` Tests: `tests/test_seed_audio.py` + `tests/test_result_artifacts.py` 53 passed, including the dubbing body carrying the presigned video URL and the subtitle travelling with it. --- .../opendirector/integrations/volcengine.py | 60 ++++++++----------- 1 file changed, 25 insertions(+), 35 deletions(-) diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index eb2f990a0..35950f656 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -238,45 +238,14 @@ async def query(): raise protocol_failure(stage) await asyncio.sleep(self.poll_interval) if kind == "audio" and is_seed_audio(config["modelId"]) and task["parameters"].get("taskType") == "dubbing": - storage = config.get("storage") or {} if not prepared["videos"]: raise ProjectError("翻配需要引用一段视频。", 422, code="audio_reference_video") - if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): - raise ProjectError("翻配需要先配置对象存储,方舟只能拉取可访问的地址。", 422, - code="seed_audio_storage") - key = f"od/{task['id']}/{uuid4()}.mp4" - media = prepared["videos"][0] - path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.mp4") - with open(path, "wb") as handle: - handle.write(media) - try: - await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], - key, path, storage["accessKey"], storage["secretKey"], - content_type="video/mp4") - except tos_transfer.TransferError as error: - raise ProjectError("视频上传失败,请检查对象存储配置后重试。", 502, - code=f"seed_audio_{error.code}") from error - finally: - os.unlink(path) - source = tos_transfer.presign(storage["bucket"], storage["region"], key, - storage["accessKey"], storage["secretKey"], expires=3600) + source = await self._publish_media(config, task["id"], prepared["videos"][0], "mp4", "video/mp4", + noun="视频") subtitle_url = None if prepared.get("subtitle"): - subtitle_key = f"od/{task['id']}/{uuid4()}.srt" - subtitle_path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.srt") - with open(subtitle_path, "wb") as handle: - handle.write(prepared["subtitle"]) - try: - await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], - subtitle_key, subtitle_path, storage["accessKey"], - storage["secretKey"], content_type="application/x-subrip") - except tos_transfer.TransferError as error: - raise ProjectError("字幕上传失败,请检查对象存储配置后重试。", 502, - code=f"seed_audio_{error.code}") from error - finally: - os.unlink(subtitle_path) - subtitle_url = tos_transfer.presign(storage["bucket"], storage["region"], subtitle_key, - storage["accessKey"], storage["secretKey"], expires=3600) + subtitle_url = await self._publish_media(config, task["id"], prepared["subtitle"], "srt", + "application/x-subrip", noun="字幕") payload = seed_audio_dubbing_body(config, source, task["parameters"], subtitle_url) stage = 'submit' async with client.stream("POST", endpoint(config["url"], "/contents/generations"), @@ -337,6 +306,27 @@ async def query(): except (ValueError, TypeError, KeyError, IndexError, AttributeError): raise protocol_failure(stage) from None + async def _publish_media(self, config, task_id, data, suffix, content_type, *, noun="素材"): + """Put one file where the provider can fetch it and return an address it may read.""" + storage = config.get("storage") or {} + if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): + raise ProjectError("该任务需要先配置对象存储,方舟只能拉取可访问的地址。", 422, + code="seed_audio_storage") + key = f"od/{task_id}/{uuid4()}.{suffix}" + path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.{suffix}") + with open(path, "wb") as handle: + handle.write(data) + try: + await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], key, path, + storage["accessKey"], storage["secretKey"], content_type=content_type) + except tos_transfer.TransferError as error: + raise ProjectError(f"{noun}上传失败,请检查对象存储配置后重试。", 502, + code=f"seed_audio_{error.code}") from error + finally: + os.unlink(path) + return tos_transfer.presign(storage["bucket"], storage["region"], key, + storage["accessKey"], storage["secretKey"], expires=3600) + async def _download(self, client, url, *, secrets=(), public_only=False): parts = urlsplit(url) if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username or parts.password: From 8bd7b47cf0b62202eb831ac0b825e7b5aaf8ce0e Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:16:09 +0800 Subject: [PATCH 23/58] [refactor] audio: decide storage readiness in one place ## summary Two call sites now need the same yes/no answer about the provider account: the upload helper itself, and the subtitle path, which has to tell "this job has a subtitle and nothing to publish it with" apart from a plain missing account before it calls the helper. Keeping the four-field test in both places would let them drift, and a drifting readiness check shows up as a wrong error code rather than a test failure. `_storage_ready(config)` holds it once and `_publish_media` asks it, so the subtitle path and the helper can never disagree about whether the same account is usable. It stays on the Ark adapter: object storage is a property of a provider that only reads remote URLs, not of every generation provider, and the base class has no other reason to know about buckets. `#650` Tests: `tests/test_seed_audio.py` + `tests/test_result_artifacts.py` 53 passed, including dubbing refused with `seed_audio_storage` before any request when no account is configured, and publishing the video and subtitle when one is. --- .../core/src/opendirector/integrations/volcengine.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index 35950f656..ec7cfdd91 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -306,12 +306,17 @@ async def query(): except (ValueError, TypeError, KeyError, IndexError, AttributeError): raise protocol_failure(stage) from None + def _storage_ready(self, config): + """Whether this account can publish media for a provider that only reads remote URLs.""" + storage = config.get("storage") or {} + return all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")) + async def _publish_media(self, config, task_id, data, suffix, content_type, *, noun="素材"): """Put one file where the provider can fetch it and return an address it may read.""" - storage = config.get("storage") or {} - if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): + if not self._storage_ready(config): raise ProjectError("该任务需要先配置对象存储,方舟只能拉取可访问的地址。", 422, code="seed_audio_storage") + storage = config["storage"] key = f"od/{task_id}/{uuid4()}.{suffix}" path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.{suffix}") with open(path, "wb") as handle: From 496e1606af0fa9615f825a3c3d4ad9fa21d6c504 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:30:57 +0800 Subject: [PATCH 24/58] [feat] assets: upload a subtitle file as a subtitle asset MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary 按字幕配音 needs an uploaded SRT, but the upload inspector only recognised `.txt` and `.md` as text. An `.srt` fell through to the media branch and came back as a generic file, so no subtitle asset could ever exist and `subtitleAssetId` was unreachable from the interface — the validation in the audio reference layer was correct and simply could never be satisfied. `.srt` now inspects as text with `application/x-subrip`, which is the type the reference layer already accepts. The size and UTF-8 checks are the existing text ones; a subtitle that is not valid SRT timings is still refused later, by the rule that owns that judgement. `#650` Tests: `tests/test_creation_assets.py::test_an_srt_upload_becomes_a_subtitle_asset` uploads a real SRT through the API and reads the bytes back; `tests/test_seed_audio.py` now asserts the reference layer accepts both `text/plain` and `application/x-subrip` subtitles. That test failed with `kind == 'file'` before `.srt` was recognised. 235 passed across the seven modules touched by this branch. --- .../src/opendirector/infrastructure/creation_uploads.py | 5 +++-- tests/test_creation_assets.py | 8 ++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/core/src/opendirector/infrastructure/creation_uploads.py b/packages/core/src/opendirector/infrastructure/creation_uploads.py index eead9a10f..88c34ab5e 100644 --- a/packages/core/src/opendirector/infrastructure/creation_uploads.py +++ b/packages/core/src/opendirector/infrastructure/creation_uploads.py @@ -59,7 +59,7 @@ def inspect_file(path: Path, name: str, *, expected_kind=None): if suffix in {'.ttf', '.otf', '.ttc', '.otc', '.woff', '.woff2'} or prefix[:4] in FONT_SIGNATURES: font = inspect_font(path) return 'file', MediaMetadata(size=size, mimeType=font.mimeType) - if suffix in {'.txt', '.md'} or expected_kind == 'text': + if suffix in {'.txt', '.md', '.srt'} or expected_kind == 'text': if size > MAX_CREATION_TEXT_BYTES: raise ProjectError('文本素材应不超过 1 MiB。', 413) try: @@ -68,7 +68,8 @@ def inspect_file(path: Path, name: str, *, expected_kind=None): raise ProjectError('文本素材需使用 UTF-8 编码。') from None if any(ord(char) < 32 and char not in '\t\r\n' for char in text): raise ProjectError('文件包含非文本内容,请导入 UTF-8 文本。') - return 'text', MediaMetadata(size=size, mimeType='text/markdown' if suffix == '.md' else 'text/plain') + mime = {'md': 'text/markdown', 'srt': 'application/x-subrip'}.get(suffix.lstrip('.'), 'text/plain') + return 'text', MediaMetadata(size=size, mimeType=mime) with path.open('rb') as stream: prefix = stream.read(16) image_bytes = (prefix.startswith((b'\x89PNG\r\n\x1a\n', b'\xff\xd8\xff', b'GIF87a', b'GIF89a')) diff --git a/tests/test_creation_assets.py b/tests/test_creation_assets.py index 03228966e..013cc5707 100644 --- a/tests/test_creation_assets.py +++ b/tests/test_creation_assets.py @@ -579,6 +579,14 @@ def test_empty_text_and_generic_files_have_safe_content_access(api): assert response.headers['content-disposition'].startswith('attachment;') +def test_an_srt_upload_becomes_a_subtitle_asset(api): + client, base, _, project_id = api + lines = '1\n00:00:00,000 --> 00:00:02,000\n你好\n\n'.encode() + info, _, asset_id = api_upload(client, base, data=lines, name='lines.srt') + assert info['kind'] == 'text' and info['metadata']['mimeType'] == 'application/x-subrip' + assert client.get(base + '/assets/' + asset_id + '/content').content == lines + + def test_clipboard_image_without_suffix_is_inspected_from_its_bytes(api): client, base, _, _ = api info, _, asset_id = api_upload(client, base, name='clipboard') From 6aa464270acaed45e867eb939dfb16b132333fa4 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:33:13 +0800 Subject: [PATCH 25/58] [feat] audio: accept the four reference shapes Seed Audio allows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary The provider takes exactly four reference combinations: one image, one video, up to six voice clips, or one video with voice clips. The adapter only ever implemented the first and third. A video fell into the "not supported" branch unless the task was dubbing, and voice clips were refused next to a video, so 视频参考生音频 and 音视频参考生音频 could not be requested at all — both are in the acceptance list for `#650`. Video is now a reference like any other. Dubbing keeps its own role `dubbing_video` and its MP4-only bound; every other task sends `reference_video` and accepts MP4 or MOV. Because the service can only fetch video from a URL, a reference video goes through the same `_publish_media` path as the dubbing source, and the declared content type follows the container brand instead of assuming MP4. The mix rule now states the real constraint: image cannot be combined with video or voice, and dubbing cannot carry voice clips. Image plus voice stays refused, as before. Three codes were added so each refusal keeps its own meaning in both languages: `audio_dubbing_video` (wrong format or length for dubbing), `audio_dubbing_source` (no source video), `audio_separation_video` (separation takes audio only). `audio_reference_video` now only means a video the service cannot accept, and `audio_reference_count` and `audio_reference_mix` were reworded to describe the wider matrix. `#650` Tests: `tests/test_seed_audio.py` covers a video travelling as `reference_video`, a video with a voice clip travelling together, the image-plus-video and separation-plus-video refusals, the declared type for both container brands, and a published video arriving in the request body. The publish test fails with an empty publish list before the adapter change. `tests/test_localization.py` answers each new code in English and Chinese. 236 passed across the seven modules touched by this branch. --- apps/api/src/opendirector_api/localization.py | 9 +- .../opendirector/domain/creation/commands.py | 2 +- .../integrations/reference_inputs.py | 25 +++-- .../opendirector/integrations/seed_audio.py | 8 +- .../opendirector/integrations/volcengine.py | 13 ++- src/contracts/creation.schema.json | 6 ++ src/contracts/generated.ts | 4 +- tests/test_localization.py | 15 +++ tests/test_seed_audio.py | 101 ++++++++++++++++-- 9 files changed, 157 insertions(+), 26 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index bcccc19d4..4a2c55321 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -65,9 +65,12 @@ 'seed_audio_base_url': 'Seed Audio 1.5 needs the Ark content-generation base URL ending in /api/v3. Add the Seed Audio preset instead.', 'audio_reference_image': 'That reference cannot be sent: Seed Audio takes PNG, JPEG or WEBP images within the size limit.', 'audio_reference_audio': 'Voice references must be WAV or MP3 and 2 to 30 seconds long.', - 'audio_reference_count': 'Seed Audio takes at most one image or six voice references, up to 180 seconds in total.', - 'audio_reference_mix': 'Seed Audio cannot combine an image reference with voice references.', - 'audio_reference_video': 'This Seed Audio adapter does not accept video references yet.', + 'audio_reference_count': 'Seed Audio takes at most one image, one video, or six voice references up to 180 seconds in total.', + 'audio_reference_mix': 'Seed Audio cannot combine these inputs: send one image, one video with optional voice clips, or voice clips alone.', + 'audio_reference_video': 'A video reference must be MP4 or MOV, 4 seconds to 6 minutes.', + 'audio_dubbing_video': 'A dubbing source must be an MP4 clip of 4 seconds to 6 minutes.', + 'audio_dubbing_source': 'Dubbing needs a source video to re-voice.', + 'audio_separation_video': 'Track separation takes one audio input and no video.', 'audio_subtitle_scope': 'A subtitle file is used only when dubbing a referenced video.', 'audio_subtitle_asset': 'The subtitle must be an SRT file within the size limit.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index ea3edabc1..f2f8d1910 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -606,7 +606,7 @@ def command_fingerprint(command: Command) -> str: 'capability_unsupported', 'preview_expired', 'storage_unavailable', 'submission_unknown', 'provider_error', 'audio_music_unsupported', 'audio_mode_required', 'audio_task_unsupported', 'seed_audio_base_url', 'audio_reference_image', 'audio_reference_audio', 'audio_reference_count', 'audio_reference_mix', - 'audio_reference_video', 'audio_subtitle_scope', 'audio_subtitle_asset', 'seed_audio_storage', 'seed_audio_storage_rejected', 'seed_audio_storage_timeout', 'seed_audio_storage_unreachable', + 'audio_reference_video', 'audio_dubbing_video', 'audio_dubbing_source', 'audio_separation_video', 'audio_subtitle_scope', 'audio_subtitle_asset', 'seed_audio_storage', 'seed_audio_storage_rejected', 'seed_audio_storage_timeout', 'seed_audio_storage_unreachable', 'moss_speech_text', 'moss_speech_voice', 'moss_speech_reference', 'moss_prompt_limit', 'moss_image_size', 'moss_image_reference', 'moss_layout_reference', 'bigmodel_image_size', 'bigmodel_image_reference', 'bigmodel_image_prompt', diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 5018f3682..4d76bf8b2 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -114,17 +114,22 @@ def seed_audio_references(store, task, rules, result, overrides): raise ProjectError(f'参考音频最多 {rules["maxAudios"]} 段、合计不超过 {budget_ms // 1000} 秒。', 422, code='audio_reference_count') result['audios'].append(data_uri(data, 'audio/wav' if meta['type'] == 'audio/x-wav' else meta['type'])) result['manifest'].append({**entry, 'role': result['audio_role']}) - elif source_kind == 'video' and dubbing: + elif source_kind == 'video': + if separating: + raise ProjectError('分轨只接收一段音频,不支持视频。', 422, code='audio_separation_video') duration = meta.get('durationMs') low, high = SEED_AUDIO_DUBBING_MS - if meta.get('type') not in {'video/mp4'} or duration is None or not low <= duration <= high: - raise ProjectError('翻配视频需为 MP4,时长 4 秒至 6 分钟。', 422, code='audio_reference_video') - if result['videos']: - raise ProjectError('翻配一次只能引用一段视频。', 422, code='audio_reference_count') + accepted = {'video/mp4'} if dubbing else {'video/mp4', 'video/quicktime'} + if meta.get('type') not in accepted or duration is None or not low <= duration <= high: + if dubbing: + raise ProjectError('翻配视频需为 MP4,时长 4 秒至 6 分钟。', 422, code='audio_dubbing_video') + raise ProjectError('参考视频需为 MP4 或 MOV,时长 4 秒至 6 分钟。', 422, code='audio_reference_video') + if len(result['videos']) >= rules['maxVideos']: + raise ProjectError('Seed Audio 1.5 一次只能引用一段视频。', 422, code='audio_reference_count') result['videos'].append(data) - result['manifest'].append({**entry, 'role': 'dubbing_video'}) + result['manifest'].append({**entry, 'role': 'dubbing_video' if dubbing else 'reference_video'}) else: - raise ProjectError(f'“{meta["name"]}”:Seed Audio 1.5 暂不接受视频参考。', 422, code='audio_reference_video') + raise ProjectError(f'“{meta["name"]}”:Seed Audio 1.5 不接受这个素材。', 422, code='audio_reference_mix') subtitle_id = (task.get('parameters') or {}).get('subtitleAssetId') if subtitle_id: if not dubbing or not result['videos']: @@ -137,8 +142,10 @@ def seed_audio_references(store, task, rules, result, overrides): result['subtitle'] = data result['manifest'].append({'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': 'text', 'transmission': 'content', 'role': 'custom_subtitle'}) - if result['videos'] and (result['images'] or result['audios']): - raise ProjectError('翻配视频不能与图片或音频参考同时使用。', 422, code='audio_reference_mix') + if result['videos'] and result['images']: + raise ProjectError('Seed Audio 1.5 的视频参考与图片参考不能同时使用。', 422, code='audio_reference_mix') + if dubbing and result['audios']: + raise ProjectError('翻配视频不能再搭配音频参考,请改用普通音频参考生成。', 422, code='audio_reference_mix') if result['images'] and result['audios']: raise ProjectError('Seed Audio 1.5 的图片参考与音频参考不能同时使用。', 422, code='audio_reference_mix') return result diff --git a/packages/core/src/opendirector/integrations/seed_audio.py b/packages/core/src/opendirector/integrations/seed_audio.py index 642b533cf..a6fb76151 100644 --- a/packages/core/src/opendirector/integrations/seed_audio.py +++ b/packages/core/src/opendirector/integrations/seed_audio.py @@ -11,10 +11,11 @@ def is_seed_audio(model_id): return isinstance(model_id, str) and model_id.startswith(MODEL_PREFIX) -def request_body(config, prompt, parameters, images=(), audios=(), audio_role='reference_audio'): +def request_body(config, prompt, parameters, images=(), audios=(), audio_role='reference_audio', videos=()): content = [{'type': 'text', 'text': prompt}] content.extend({'type': 'image_url', 'role': 'reference_image', 'image_url': {'url': image}} for image in images) content.extend({'type': 'audio_url', 'role': audio_role, 'audio_url': {'url': audio}} for audio in audios) + content.extend({'type': 'video_url', 'role': 'reference_video', 'video_url': {'url': video}} for video in videos) body = {'model': config['modelId'], 'content': content, 'output_format': parameters.get('output_format') or 'mp3'} audio = {key: parameters[key] for key in @@ -40,6 +41,11 @@ def dubbing_body(config, video_url, parameters, subtitle_url=None): return body +def video_type(data): + brand = data[8:12] if data[4:8] == b'ftyp' else b'' + return 'video/quicktime' if brand in {b'qt ', b'qt'} else 'video/mp4' + + def artifact_suffix(url, allowed, default): suffix = urlsplit(url).path.rsplit('.', 1)[-1].lower() return suffix if suffix in allowed else default diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index ec7cfdd91..2421b41a1 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -20,7 +20,7 @@ from opendirector.integrations.generation_errors import checked, protocol_failure, provider_failure, transport_failure from opendirector.integrations.seed_audio import (audio_artifacts as seed_audio_artifacts, is_seed_audio, dubbing_artifacts as seed_audio_dubbing_artifacts, dubbing_body as seed_audio_dubbing_body, - request_body as seed_audio_body) + request_body as seed_audio_body, video_type as seed_audio_video_type) from opendirector.integrations import tos_transfer from opendirector.media.probe import require_ffprobe @@ -239,7 +239,7 @@ async def query(): await asyncio.sleep(self.poll_interval) if kind == "audio" and is_seed_audio(config["modelId"]) and task["parameters"].get("taskType") == "dubbing": if not prepared["videos"]: - raise ProjectError("翻配需要引用一段视频。", 422, code="audio_reference_video") + raise ProjectError("翻配需要引用一段视频。", 422, code="audio_dubbing_source") source = await self._publish_media(config, task["id"], prepared["videos"][0], "mp4", "video/mp4", noun="视频") subtitle_url = None @@ -260,9 +260,16 @@ async def query(): await extra_ready(role, variant, track, extra_suffix, url) return artifacts[0][2], await self._download(client, artifacts[0][1], secrets=secrets) if kind == "audio" and is_seed_audio(config["modelId"]): + videos = [] + for data in prepared['videos']: + content_type = seed_audio_video_type(data) + videos.append(await self._publish_media( + config, task["id"], data, "mov" if content_type == "video/quicktime" else "mp4", + content_type, noun="视频")) payload = seed_audio_body(config, prompt, task["parameters"], prepared['images'], prepared['audios'], - audio_role=prepared.get('audio_role', 'reference_audio')) + audio_role=prepared.get('audio_role', 'reference_audio'), + videos=videos) request_size(payload, prepared['rules']['requestBytes']) async with client.stream("POST", endpoint(config["url"], "/contents/generations"), headers=headers, json=payload) as response: diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 43ff2231d..b1b6427b7 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4784,6 +4784,9 @@ "audio_reference_count", "audio_reference_mix", "audio_reference_video", + "audio_dubbing_video", + "audio_dubbing_source", + "audio_separation_video", "audio_subtitle_scope", "audio_subtitle_asset", "seed_audio_storage", @@ -25184,6 +25187,9 @@ "audio_reference_count", "audio_reference_mix", "audio_reference_video", + "audio_dubbing_video", + "audio_dubbing_source", + "audio_separation_video", "audio_subtitle_scope", "audio_subtitle_asset", "seed_audio_storage", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 05ecbc556..8e9c9ceb8 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -513,7 +513,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_dubbing_video" | "audio_dubbing_source" | "audio_separation_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -2586,7 +2586,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_dubbing_video" | "audio_dubbing_source" | "audio_separation_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId: string | null; readonly field: string | null; diff --git a/tests/test_localization.py b/tests/test_localization.py index 97def31eb..cf0ffd624 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -40,6 +40,21 @@ def test_a_side_artifact_is_refused_in_the_interface_language(): assert localized_error(request('zh-CN'), chinese=chinese, status=422, code=code) == chinese +def test_a_video_reference_is_refused_in_the_interface_language(): + for code, chinese, english in [ + ('audio_reference_video', '参考视频需为 MP4 或 MOV,时长 4 秒至 6 分钟。', + 'A video reference must be MP4 or MOV, 4 seconds to 6 minutes.'), + ('audio_dubbing_video', '翻配视频需为 MP4,时长 4 秒至 6 分钟。', + 'A dubbing source must be an MP4 clip of 4 seconds to 6 minutes.'), + ('audio_dubbing_source', '翻配需要引用一段视频。', + 'Dubbing needs a source video to re-voice.'), + ('audio_separation_video', '分轨只接收一段音频,不支持视频。', + 'Track separation takes one audio input and no video.'), + ]: + assert localized_error(request('en-US'), chinese=chinese, status=422, code=code) == english + assert localized_error(request('zh-CN'), chinese=chinese, status=422, code=code) == chinese + + def test_accept_language_uses_the_primary_language() -> None: assert wants_english(request("zh-CN,zh;q=0.9")) is False assert wants_english(request("zh-Hant")) is False diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index bd6dd7bb6..acdf91342 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -16,7 +16,7 @@ from opendirector.domain.input_rules import input_rules from opendirector.domain.projects import ProjectError from opendirector.integrations.seed_audio import (audio_artifacts, dubbing_artifacts, dubbing_body, - request_body) + request_body, video_type) from opendirector.integrations.volcengine import VolcengineGeneration from test_creation_contracts import entity, model as public_model from test_creation_canvas_service import project # noqa: F401 (pytest fixture) @@ -232,15 +232,55 @@ def test_voice_references_must_be_two_to_thirty_seconds(tmp_path): assert failure.value.code == 'audio_reference_audio' -def test_video_references_stay_unsupported(tmp_path): +def test_a_video_reference_travels_as_a_reference_video(tmp_path, monkeypatch): store, owner, _, _, _ = reference_store(tmp_path) video = {'id': str(UUID(int=40)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', 'fingerprint': 'fixture', 'durationMs': 5000} original = store.asset store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + ready = prepared(store, owner, [video]) + assert len(ready['videos']) == 1 and ready['audios'] == [] and ready['images'] == [] + assert [entry['role'] for entry in ready['manifest']] == ['reference_video'] + body = request_body(config(), ready['prompt'], {'output_format': 'mp3'}, ready['images'], + ready['audios'], videos=['https://storage.example/od/clip.mp4']) + assert body['content'][-1] == {'type': 'video_url', 'role': 'reference_video', + 'video_url': {'url': 'https://storage.example/od/clip.mp4'}} + + +def test_a_video_and_a_voice_reference_travel_together(tmp_path): + store, owner, _, voice, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=41)), 'name': '片段.mov', 'type': 'video/quicktime', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': 8000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + ready = prepared(store, owner, [video, voice]) + assert len(ready['videos']) == 1 and len(ready['audios']) == 1 + assert [entry['role'] for entry in ready['manifest']] == ['reference_video', 'reference_audio'] + + +def test_a_video_reference_cannot_be_mixed_with_an_image(tmp_path): + store, owner, image, _, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=42)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': 5000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + with pytest.raises(ProjectError) as failure: + prepared(store, owner, [image, video]) + assert failure.value.code == 'audio_reference_mix' + + +def test_separation_takes_no_video(tmp_path): + store, owner, _, _, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=43)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': 5000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + task = store_task(owner, [video]) + task['parameters']['taskType'] = 'separation' + from opendirector.integrations.reference_inputs import generation_references with pytest.raises(ProjectError) as failure: - prepared(store, owner, [video]) - assert failure.value.code == 'audio_reference_video' + generation_references(store, task, config()) + assert failure.value.code == 'audio_separation_video' def dubbing_task(owner, refs, **parameters): @@ -345,7 +385,7 @@ def test_dubbing_rejects_a_video_outside_the_accepted_duration(tmp_path): store, owner, video = dubbing_store(tmp_path, 3000) with pytest.raises(ProjectError) as failure: dubbing_ready(store, owner, [video]) - assert failure.value.code == 'audio_reference_video' + assert failure.value.code == 'audio_dubbing_video' def test_dubbing_cannot_mix_a_video_with_voice_samples(tmp_path): @@ -368,9 +408,10 @@ def test_dubbing_carries_a_custom_subtitle_url(tmp_path): assert ready['subtitle'] is None -def test_a_subtitle_asset_travels_with_the_dubbed_video(tmp_path): +@pytest.mark.parametrize('mime', ['text/plain', 'application/x-subrip']) +def test_a_subtitle_asset_travels_with_the_dubbed_video(tmp_path, mime): store, owner, video = dubbing_store(tmp_path, 6000) - srt = {'id': str(UUID(int=60)), 'name': '台词.srt', 'type': 'text/plain', 'kind': 'text', + srt = {'id': str(UUID(int=60)), 'name': '台词.srt', 'type': mime, 'kind': 'text', 'fingerprint': 'fixture'} original = store.asset body = b'1\n00:00:00,000 --> 00:00:02,000\n\n' @@ -463,6 +504,52 @@ def handler(request): 'audio_url': {'url': 'data:audio/wav;base64,AAAA'}} +def test_the_declared_video_type_follows_the_container_brand(): + assert video_type(b'\x00\x00\x00\x18ftypmp42') == 'video/mp4' + assert video_type(b'\x00\x00\x00\x14ftypqt ') == 'video/quicktime' + + +@pytest.mark.anyio +async def test_a_video_reference_is_published_before_the_request(monkeypatch): + from opendirector.integrations import volcengine as module + audio = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', + 'sine=frequency=440:sample_rate=44100', '-t', '0.2', + '-threads', '1', '-f', 'mp3', 'pipe:1'], + capture_output=True, check=True).stdout + posted = [] + + def handler(request): + if request.method == 'GET': + return httpx.Response(200, content=audio, headers={'content-type': 'audio/mpeg'}) + posted.append(json.loads(request.content)) + return httpx.Response(200, json={'id': '0219', 'model': MODEL, + 'content': {'audios': [{'url': 'http://fixture.invalid/api/v3/mix.mp3'}]}}) + + clip = b'\x00\x00\x00\x18ftypmp42' + ready = {'prompt': '跟着画面配一段动效声。', 'images': [], 'audios': ['data:audio/wav;base64,AAAA'], + 'videos': [clip], 'manifest': [], 'subtitle': None, 'continueFrom': None, + 'continueSize': None, 'control': None, 'guides': [], 'audio_role': 'reference_audio', + 'rules': input_rules({**config(), 'kind': 'audio'})} + monkeypatch.setattr(module, 'generation_references', lambda store, task, configuration: ready) + published = [] + + async def publish(configuration, task_id, data, suffix, content_type, *, noun='素材'): + published.append((data, suffix, content_type, noun)) + return 'https://storage.example/od/clip.mp4' + + monkeypatch.setattr(VolcengineGeneration, '_publish_media', staticmethod(publish)) + provider = VolcengineGeneration(None, transport=httpx.MockTransport(handler), poll_interval=0) + task = {'id': 'job', 'kind': 'audio', 'projectId': 'p', 'prompt': '跟着画面配一段动效声。', + 'referenceIds': ['asset'], 'parameters': {'taskType': 'reference', 'output_format': 'mp3'}} + suffix, _ = await provider.generate({**config(), 'apiKey': 'fixture-key'}, task, lambda external_id: None) + assert suffix == 'mp3' + assert published == [(clip, 'mp4', 'video/mp4', '视频')] + assert posted[0]['content'][-1] == {'type': 'video_url', 'role': 'reference_video', + 'video_url': {'url': 'https://storage.example/od/clip.mp4'}} + assert posted[0]['content'][1] == {'type': 'audio_url', 'role': 'reference_audio', + 'audio_url': {'url': 'data:audio/wav;base64,AAAA'}} + + def test_separation_refuses_more_than_six_minutes_in_one_clip(tmp_path): store, owner, _, _, _ = reference_store(tmp_path) too_long = {'id': str(UUID(int=71)), 'name': '长访谈.wav', 'type': 'audio/wav', 'kind': 'audio', From 66d6bb0670da3878852412e565e8f4d3dbe2411c Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:56:16 +0800 Subject: [PATCH 26/58] [bugfix] canvas: let a video feed a dubbing node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary A video node could not feed a dubbing node. The canvas type matrix let an audio node take a video only from an image, so `reference.add` answered `reference_invalid` for exactly the reference dubbing needs and the assistant could not start the job at all. Both tables change together because the assembly test asserts the Python set and the TypeScript table are the same product truth. ## verification - `Ran:` tests/test_creation_assembly.py, tests/test_agent_seed_audio.py - Before the change the assistant test failed in `reference.add` with `reference_invalid` "该节点类型不能作为目标节点的参考。" --- packages/core/src/opendirector/application/creation_canvas.py | 2 +- src/canvas/connectionPolicy.ts | 2 +- tests/canvasReferenceMigration.test.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 339149a28..24b95d783 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -32,7 +32,7 @@ 'reference': 'references', 'editor_document': 'editorDocuments', 'asset': 'assets', 'job': 'jobs', 'result': 'results'} DOWNSTREAM = {'text': {'text', 'image', 'video', 'motion'}, 'image': {'text', 'image', 'video', 'audio', 'timeline', 'subject', 'motion'}, - 'video': {'text', 'video', 'timeline', 'subject', 'motion'}, 'audio': {'text', 'video', 'audio', 'timeline', 'motion'}, + 'video': {'text', 'video', 'audio', 'timeline', 'subject', 'motion'}, 'audio': {'text', 'video', 'audio', 'timeline', 'motion'}, 'subject': {'image', 'video', 'audio'}} diff --git a/src/canvas/connectionPolicy.ts b/src/canvas/connectionPolicy.ts index 3508ffd4a..f99a9422b 100644 --- a/src/canvas/connectionPolicy.ts +++ b/src/canvas/connectionPolicy.ts @@ -25,7 +25,7 @@ export const downstreamKinds: Partial< > = { text: ["text", "image", "video", "motion"], image: ["text", "image", "video", "audio", "timeline", "subject", "motion"], - video: ["text", "video", "timeline", "subject", "motion"], + video: ["text", "video", "audio", "timeline", "subject", "motion"], audio: ["text", "video", "audio", "timeline", "motion"], subject: ["image", "video", "audio"], }; diff --git a/tests/canvasReferenceMigration.test.ts b/tests/canvasReferenceMigration.test.ts index c7f6488b0..b5beb4d39 100644 --- a/tests/canvasReferenceMigration.test.ts +++ b/tests/canvasReferenceMigration.test.ts @@ -40,7 +40,7 @@ const kinds = [ const allowed: Record<(typeof kinds)[number], readonly CanvasNodeKind[]> = { text: ["text", "image", "video"], image: ["text", "image", "video", "audio", "subject", "timeline"], - video: ["text", "video", "subject", "timeline"], + video: ["text", "video", "audio", "subject", "timeline"], audio: ["text", "video", "audio", "timeline"], subject: ["image", "video", "audio"], timeline: [], From 01ec1911b4c802626cf39b7c8f65a5f52921af31 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:56:46 +0800 Subject: [PATCH 27/58] [bugfix] canvas: send an audio node the media its model declares MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary Every media reference attached to an audio generation was demoted to `context_only`, so no image, video or voice clip could ever reach the provider. The audio branch was written when an audio node meant speech or music, and only a music recording was allowed through; Seed Audio dubbing, separation and reference tasks all take media, and their declared capability contract already says so. Transmission now follows the same capability contract the rest of the product uses: a media kind the model accepts, with a remaining slot for that kind, travels as `content`; anything else stays `context_only`. ## verification - `Ran:` tests/test_seed_audio.py, tests/test_agent_seed_audio.py, tests/test_creation_parameters.py - Without the change the assistant test failed before any request with "翻配需要引用一段视频。" because the accepted video never left the project. --- .../core/src/opendirector/application/creation_canvas.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 24b95d783..a541239af 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -144,9 +144,10 @@ def reference_policy(spec, values, rules=None, *, selected_frame=False): frame_roles = set(rules.frameRoles) if rules and rules.frameRoles else {'first_frame'} for value in values: kind = value.asset.kind - # Speech reads its own text; only a music model that follows a recording takes one. - ignored = spec.kind == 'audio' and not (kind == 'audio' and spec.parameters.creationType == 'music' - and rules is not None and 'audio' in rules.allowedKinds) + accepted = rules is not None and kind in rules.allowedKinds and not ( + (kind == 'image' and not rules.maxImages) or (kind == 'video' and not rules.maxVideos) + or (kind == 'audio' and not rules.maxAudios)) + ignored = spec.kind == 'audio' and not (kind in {'image', 'video', 'audio'} and accepted) if spec.kind == 'video' and spec.parameters.videoMode == 'first_frame': ignored = kind not in {'text', 'image'} or kind == 'image' and (value.subjectRole is not None or not selected_frame or value.role not in frame_roles) if selected_frame and value.role in {'first_frame', 'last_frame'} and ignored: From dea40b8ef76434e6fca0ac1c63c1ed87d403a029 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:57:27 +0800 Subject: [PATCH 28/58] [bugfix] audio: run the operation Seed Audio declares and record what it returns ## summary The Seed Audio route never ran the operation the task asked for. The parameter builder wrote the operation under `task`, while the adapter and the reference builder read `taskType`, so dubbing and separation fell back to plain text-to-audio: a dubbing job carried no video and the provider answered with an ordinary speech file the project accepted as a success. Dubbing also returns a re-voiced video rather than audio, which the job contract refused: an audio execution could only own an audio asset. The execution record now names the media the provider delivers, and the result is registered with that kind instead of the model kind. ## verification - `Ran:` tests/test_agent_seed_audio.py, tests/test_seed_audio.py, tests/test_creation_parameters.py, tests/test_creation_generation_service.py, tests/test_creation_contracts.py - Without the parameter change the assistant test posted a text-only body and failed on the missing `video_url`. - Without the delivered-kind record the same test failed at save with "Job execution/output kind differs from its inputs". --- .../application/creation_generation.py | 14 ++++---- .../domain/creation/generation.py | 5 ++- src/contracts/creation.schema.json | 34 +++++++++++++++++++ src/contracts/generated.ts | 2 ++ 4 files changed, 48 insertions(+), 7 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index e17b46ba5..7b3923448 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -214,7 +214,7 @@ def _parameters(self, spec, config, node, records): if intent.get('durationFromReference', True) and recording['durationMs']: params['duration'] = reference_music_seconds(recording['durationMs'] / 1000) elif spec.kind == 'audio' and input_rules(config)['profile'] == 'seed-audio': - params = {'task': intent.get('taskType', 'text2audio'), + params = {'taskType': intent.get('taskType', 'text2audio'), 'output_format': intent.get('outputFormat', 'mp3')} for key, name in (('speech_rate', 'speechRate'), ('loudness_rate', 'loudnessRate'), ('pitch_rate', 'pitchRate')): @@ -312,7 +312,8 @@ def _execution(kind, parameters, config): return dict(kind=kind, creationType='music', format='mp3', maxDurationSeconds=parameters['duration'], scoreMode=parameters.get('score_mode'), seed=parameters.get('seed')) if kind == 'audio' and input_rules(config)['profile'] == 'seed-audio': - return dict(kind=kind, taskType=parameters.get('task', 'text2audio'), + return dict(kind=kind, taskType=parameters['taskType'], + outputKind='video' if parameters['taskType'] == 'dubbing' else None, format=parameters.get('output_format', 'mp3'), sampleRate=parameters.get('sample_rate'), speechRate=parameters.get('speech_rate'), loudnessRate=parameters.get('loudness_rate'), pitchRate=parameters.get('pitch_rate'), @@ -599,9 +600,10 @@ def _commit_output(self, task, pinned, suffix, data): job = self.get_job(task['projectId'], task['id']) handle = uuid5(job.id, 'output-upload') name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', task['title']).strip(' .')[:180] or job.execution.kind + primary_kind = getattr(job.execution, 'outputKind', None) or artifact_kind(suffix) or job.execution.kind if not existing: self.assets.stage_output(job.projectId, handle, with_extension(name, suffix), - cache.directory / 'output', expected_kind=job.execution.kind) + cache.directory / 'output', expected_kind=primary_kind) staged = [(uuid5(job.id, f"output-upload:{record['role']}:{record.get('variant') or ''}:{record.get('track') or ''}"), with_extension(self._artifact_name(name, record), record['suffix']), artifact_kind(record['suffix']), record) @@ -615,7 +617,7 @@ def _commit_output(self, task, pinned, suffix, data): # the provider request or reusing an obsolete adoption decision. for attempt in range(16): try: - return self._register_output(task, pinned, suffix, handle, name, staged) + return self._register_output(task, pinned, suffix, handle, name, staged, primary_kind) except ProjectError as error: if error.code != 'revision_conflict' or attempt == 15: raise @@ -626,7 +628,7 @@ def _artifact_name(name, record): if part and part != 'primary'] return f"{name}-{'-'.join(parts)}" if parts else name - def _register_output(self, task, pinned, suffix, handle, name, staged=()): + def _register_output(self, task, pinned, suffix, handle, name, staged=(), kind=None): before = self.projects.snapshot(task['projectId']) job = next(j for j in before.jobs if str(j.id) == task['id']) if job.status == 'succeeded': @@ -639,7 +641,7 @@ def _register_output(self, task, pinned, suffix, handle, name, staged=()): origin = next((i for i in before.canvasItems if i.id == job.originItemId), None) command = parse_command(dict(commandId=uuid5(job.id, f'register-result:{job.revision}:{spec.revision}:{origin.revision if origin else 0}'), projectId=job.projectId, type='asset.import', expectedVersions=[version('job', job), version('generation_spec', spec), *([version('canvas_item', origin)] if origin else [])], - payload=dict(uploadHandle=handle, name=with_extension(name, suffix), expectedKind=job.execution.kind))) + payload=dict(uploadHandle=handle, name=with_extension(name, suffix), expectedKind=kind or job.execution.kind))) extras = [(gateway().upload_asset_id(job.projectId, extra_handle), record) for extra_handle, _, _, record in staged] def apply(current, asset): current_job = next(j for j in current.jobs if j.id == job.id) diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 17c3b7fe9..8ae4abc46 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -335,6 +335,8 @@ class AudioExecution(Contract): subtitleAssetId: UUID | None = Field(default=None, exclude_if=lambda value: value is None, description='Dubbing: subtitle asset that fixed the spoken lines when the job was accepted.') creationType: Literal['audio', 'music'] = Field(default='audio', exclude_if=lambda value: value == 'audio', description='Speech or music creation mode.') + outputKind: Literal['audio', 'video'] | None = Field(default=None, exclude_if=lambda value: value is None, + description='Media the provider delivers when it differs from the model kind, as a re-voiced video does.') # Legacy, see AudioParameters.instrumental. instrumental: bool = Field(default=False, exclude_if=lambda value: value is False, description='Legacy explicit instrumental choice retained for stored records.') # A music model may end the piece earlier than this cap. @@ -390,7 +392,8 @@ def execution_identity(self): raise ValueError('Job and generation snapshot belong to different projects') if self.inputFingerprint != self.inputSnapshot.fingerprint(): raise ValueError('Job input fingerprint differs from its snapshot') - if self.execution.kind != self.inputSnapshot.spec.kind or self.asset and self.asset.kind != self.execution.kind: + output = getattr(self.execution, 'outputKind', None) or self.execution.kind + if self.execution.kind != self.inputSnapshot.spec.kind or self.asset and self.asset.kind != output: raise ValueError('Job execution/output kind differs from its inputs') if self.status == 'succeeded' and self.asset is None: raise ValueError('Successful jobs require an actual output asset') diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index b1b6427b7..50c90de66 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -1377,6 +1377,23 @@ "title": "Creationtype", "type": "string" }, + "outputKind": { + "anyOf": [ + { + "enum": [ + "audio", + "video" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Media the provider delivers when it differs from the model kind, as a re-voiced video does.", + "title": "Outputkind" + }, "instrumental": { "default": false, "description": "Legacy explicit instrumental choice retained for stored records.", @@ -21694,6 +21711,23 @@ "title": "Creationtype", "type": "string" }, + "outputKind": { + "anyOf": [ + { + "enum": [ + "audio", + "video" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Media the provider delivers when it differs from the model kind, as a re-voiced video does.", + "title": "Outputkind" + }, "instrumental": { "default": false, "description": "Legacy explicit instrumental choice retained for stored records.", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 8e9c9ceb8..775a7ebcb 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -139,6 +139,7 @@ export interface AudioExecutionInput extends ContractInput { readonly sourceLanguage?: string | null; readonly subtitleAssetId?: string | null; readonly creationType?: "audio" | "music"; + readonly outputKind?: "audio" | "video" | null; readonly instrumental?: boolean; readonly maxDurationSeconds?: number | null; readonly scoreMode?: "melody" | "full" | null; @@ -2212,6 +2213,7 @@ export interface AudioExecution extends Contract { readonly sourceLanguage?: string | null; readonly subtitleAssetId?: string | null; readonly creationType?: "audio" | "music"; + readonly outputKind?: "audio" | "video" | null; readonly instrumental?: boolean; readonly maxDurationSeconds?: number | null; readonly scoreMode?: "melody" | "full" | null; From a0b38d876dcab5df9661af821c252b0591694997 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:57:33 +0800 Subject: [PATCH 29/58] [bugfix] models: build the public model shape in one place ## summary Four call sites rebuilt `ModelConfigPublic` by copying the resolved service record and dropping only `apiKey`. Once a model service also carried its object-storage credentials, the strict public shape rejected the extra key and every spec projection failed with `invalid_input: "storage: Extra inputs are not permitted"`, which reached the user as a refusal to submit work at all. One factory drops everything the public shape must never carry, so a future service-level field cannot break submission again. ## verification - `Ran:` tests/test_agent_seed_audio.py, tests/test_creation_parameters.py, tests/test_creation_canvas_service.py, tests/test_creation_node_versions.py - Before the change the assistant test failed with `invalid_input: "storage: Extra inputs are not permitted"` before any request was sent. --- .../core/src/opendirector/application/creation_canvas.py | 2 +- .../core/src/opendirector/application/creation_generation.py | 4 ++-- .../src/opendirector/application/creation_node_versions.py | 2 +- packages/core/src/opendirector/domain/creation/models.py | 5 +++++ 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index a541239af..13c301eef 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -985,7 +985,7 @@ def projection(self, project_id, snapshot=None): key = (str(spec.modelConfigId), spec.kind) if key not in public_models: config = models.resolve(str(spec.modelConfigId), 'agent' if spec.kind == 'text' else spec.kind) - public_models[key] = ModelConfigPublic.model_validate({k: v for k, v in config.items() if k != 'apiKey'} | {'inputRules': input_rules(config)}) + public_models[key] = ModelConfigPublic.from_service(config, input_rules(config)) model = public_models[key] spec, references = current_generation_inputs(snapshot, spec, model.inputRules, visible) for reference in references: diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 7b3923448..2053de074 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -402,7 +402,7 @@ def prepare(self, command, *, session=None, source='ui', agent_origin=None): if voice_spec is not None and voice_spec.kind == 'audio' and voice_spec.parameters.creationType == 'audio': try: voice_config = self.configs.resolve(str(voice_spec.modelConfigId), 'audio') - public = ModelConfigPublic.model_validate({key: value for key, value in voice_config.items() if key != 'apiKey'} | {'inputRules': input_rules(voice_config)}) + public = ModelConfigPublic.from_service(voice_config, input_rules(voice_config)) prepared_spec, references = current_generation_inputs(initial, voice_spec, public.inputRules) validate_generation(prepared_spec, public, references) self.voices.validate_selection(voice_config, prepared_spec.parameters.voice, prepared_spec.parameters.voiceSelection) @@ -440,7 +440,7 @@ def accept(before): intermediate = ProjectSnapshot.model_validate(data) spec = next(s for s in intermediate.generationSpecs if s.id == old.id) config = self.configs.resolve(str(spec.modelConfigId), 'agent' if spec.kind == 'text' else spec.kind) - public = ModelConfigPublic.model_validate({key: value for key, value in config.items() if key != 'apiKey'} | {'inputRules': self.availability.effective_input_rules(config)}) + public = ModelConfigPublic.from_service(config, self.availability.effective_input_rules(config)) spec, resolved = current_generation_inputs(intermediate, spec, public.inputRules) spec = execution_spec(spec, resolved, public.inputRules) try: diff --git a/packages/core/src/opendirector/application/creation_node_versions.py b/packages/core/src/opendirector/application/creation_node_versions.py index 089ea7514..30ba3cb68 100644 --- a/packages/core/src/opendirector/application/creation_node_versions.py +++ b/packages/core/src/opendirector/application/creation_node_versions.py @@ -37,7 +37,7 @@ def available_model(projects, frozen): """A removed or repurposed model remains evidence, never an implicit fallback.""" try: config = gateway().models(projects.local.repository).resolve(str(frozen.modelConfigId), frozen.kind) - public = ModelConfigPublic.model_validate({k: v for k, v in config.items() if k != 'apiKey'} | {'inputRules': input_rules(config)}) + public = ModelConfigPublic.from_service(config, input_rules(config)) fields = ('kind', 'url', 'modelId', 'protocol', 'connectionType', 'videoAdapter') if any(getattr(public, field) != getattr(frozen, field) for field in fields): return None diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index cd2366fed..4d7acfd24 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -251,6 +251,11 @@ class ModelConfigPublic(ModelConnection): availability: ModelAvailability | None = Field(default=None, exclude_if=lambda value: value is None, description='Ephemeral observation, never persisted in project snapshots.') + @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}) + class ModelConfigWrite(ModelConnection): """Only the model-settings write boundary accepts a credential.""" From 46154e503486c1437367b7646ca3eae053d1b76c Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:57:39 +0800 Subject: [PATCH 30/58] [test] agent: dub a video through the assistant ## summary Every Seed Audio test built its own task dictionary, so the assistant and canvas path was never exercised: parameter projection, reference transmission, the outbound body and result registration could each break while the suite stayed green. These tests drive `execute_command` the way the agent does and check the request that left the process, the files that came back, and the timeline that can hold the extra voice track. Writing them exposed four real defects: the video node could not reference the audio node, the reference was demoted to `context_only`, the operation key was never read, and an audio execution could not own the video that dubbing returns. ## verification - `Ran:` tests/test_agent_seed_audio.py - The request assertion requires a `dubbing_video` reference and no text. - The timeline assertion requires the generated composite track to be placeable as an audio clip beside the dubbed video. --- tests/test_agent_seed_audio.py | 170 +++++++++++++++++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 tests/test_agent_seed_audio.py diff --git a/tests/test_agent_seed_audio.py b/tests/test_agent_seed_audio.py new file mode 100644 index 000000000..8a114b22c --- /dev/null +++ b/tests/test_agent_seed_audio.py @@ -0,0 +1,170 @@ +"""Dubbing submitted the way the assistant submits it: one command, real artifacts. + +The canvas and the assistant share the same service, so this test drives the +agent tool gateway instead of calling the command directly and checks the +resulting project, request body and files. +""" +import json +import shutil +import subprocess +from uuid import UUID, uuid4 + +import httpx +import pytest + +from opendirector.agent.tools import AgentTools +from opendirector.application.creation_canvas import asset_ref +from opendirector.application.creation_tool_assets import CreationToolAssets +from opendirector.integrations import volcengine as module +from opendirector.infrastructure.model_configs import ModelConfigs +from test_creation_canvas_service import project, send, ver # noqa: F401 (pytest fixtures) +from test_creation_generation_service import anyio_backend # noqa: F401 (pytest fixture) +from test_creation_parameters import done, setup +from test_seed_audio import CONTENT_BASE, MODEL + + +pytestmark = pytest.mark.cpu + + +def ffmpeg(*arguments): + return subprocess.run(['ffmpeg', '-v', 'error', *arguments, '-threads', '1', 'pipe:1'], + capture_output=True, check=True).stdout + + +def clip(seconds=5): + return ffmpeg('-f', 'lavfi', '-i', f'color=c=teal:s=160x120:d={seconds}:r=12', + '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-movflags', 'frag_keyframe+empty_moov', + '-f', 'mp4') + + +def wav(seconds=0.3, frequency=440): + return ffmpeg('-f', 'lavfi', '-i', f'sine=frequency={frequency}:sample_rate=44100', + '-t', str(seconds), '-f', 'mp3') + + +def storage_account(runner, spec, monkeypatch): + runner.configs.save_storage(str(spec.modelConfigId), {'accessKey': 'ak', 'secretKey': 'sk', + 'bucket': 'bucket-a', 'region': 'cn-beijing'}) + monkeypatch.setattr(module.tos_transfer, 'put', lambda *arguments, **keywords: None) + monkeypatch.setattr(module.tos_transfer, 'presign', + lambda bucket, region, key, access_key, secret_key, expires=0: + f'https://tos.example/{key}') + + +async def dubbed(project, tmp_path, monkeypatch): + store, pid, session = project + assets = CreationToolAssets(store) + record = assets.import_file(str(pid), str(UUID(int=70)), 'clase.mp4', clip(), session) + video = assets.assets.get(pid, record['id']) + dubbed, track, subtitle = clip(5), wav(), b'1\n00:00:00,000 --> 00:00:01,000\nHello\n' + posted = [] + + def handler(request): + if request.method == 'GET': + suffix = request.url.path.rsplit('.', 1)[-1] + body, kind = {'mp4': (dubbed, 'video/mp4'), 'mp3': (track, 'audio/mpeg'), + 'srt': (subtitle, 'application/x-subrip')}[suffix] + return httpx.Response(200, content=body, headers={'content-type': kind}) + posted.append(json.loads(request.content)) + return httpx.Response(200, json={'content': { + 'video_url': 'http://fixture.invalid/api/v3/dubbed.mp4', + 'audios': [{'url': 'http://fixture.invalid/api/v3/mix.mp3', 'type': 'composite'}], + 'subtitles': [{'format': 'srt', 'url': 'http://fixture.invalid/api/v3/line.srt'}]}}) + + runner, item, spec_id = setup(project, 'audio', dict( + mode='unified', creationType='audio', taskType='dubbing', targetLanguage='en', + outputFormat='mp3'), handler, protocol='volcengine', model=MODEL, url=CONTENT_BASE) + snapshot = store.snapshot(pid) + spec = next(s for s in snapshot.generationSpecs if s.id == spec_id) + current = next(i for i in snapshot.canvasItems if i.id == item.id) + storage_account(runner, spec, monkeypatch) + source = uuid4() + assert send(store, pid, 'canvas.show', session=session, item=dict( + id=source, projectId=pid, kind='video', + binding=dict(role='material', objectRef=asset_ref(video)))).status == 'applied' + assert send(store, pid, 'reference.add', session=session, + versions=[ver('generation_spec', spec), ver('canvas_item', current)], + reference=dict(id=uuid4(), projectId=pid, targetSpecId=spec_id, order=1, + binding='follow_current', source=dict(id=source), + role='reference')).status == 'applied' + + business = AgentTools(store, runner, ModelConfigs(tmp_path)) + snapshot = store.snapshot(pid) + spec = next(s for s in snapshot.generationSpecs if s.id == spec_id) + current = next(i for i in snapshot.canvasItems if i.id == item.id) + turn = uuid4() + receipt = await business.execute( + pid, turn, session, 'call-1', 'execute_command', + {'type': 'generation.submit', + 'expectedVersions': [ver('generation_spec', spec), ver('canvas_item', current)], + 'payload': {'specId': str(spec_id), 'expectedSpecRevision': spec.revision, + 'originItemId': str(item.id)}}, + [], None) + assert receipt['status'] == 'accepted', receipt + await done(runner) + + (body,) = posted + assert body['content'] == [{'type': 'video_url', 'role': 'dubbing_video', + 'video_url': {'url': body['content'][0]['video_url']['url']}}] + assert body['dubbing_config'] == {'target_language': 'en'} + assert 'text' not in body + + after = store.snapshot(pid) + job = after.jobs[-1] + assert job.status == 'succeeded', job.errorDetails + return runner, store, pid, session, turn, body, after + + +def job_of(snapshot, turn): + return next(job for job in snapshot.jobs if job.agentRunId == turn) + + +@pytest.mark.anyio +async def test_the_assistant_dubs_a_video_into_the_target_language(project, tmp_path, monkeypatch): + runner, store, pid, session, turn, body, after = await dubbed(project, tmp_path, monkeypatch) + assert body['content'] == [{'type': 'video_url', 'role': 'dubbing_video', + 'video_url': {'url': body['content'][0]['video_url']['url']}}] + assert body['dubbing_config'] == {'target_language': 'en'} + assert 'text' not in body + + job = job_of(after, turn) + assert job.inputSnapshot.spec.parameters.targetLanguage == 'en' + assert job.inputSnapshot.spec.parameters.taskType == 'dubbing' + assert [(entry.role, entry.asset.kind) for entry in job.inputSnapshot.references] == [('reference', 'video')] + assert job.execution.outputKind == 'video' + assert sorted(r.role for r in after.results if r.jobId == job.id) == ['audio_track', 'primary', 'subtitle'] + adopted = next(a for a in after.assets if a.id == job.asset.assetId) + assert adopted.kind == 'video' + names = sorted(a.name for a in after.assets if a.provenance.jobId == job.id) + assert names == ['Make an output-audio_track-composite-0.mp3', 'Make an output-subtitle-target_srt.srt', + 'Make an output.mp4'], names + + +@pytest.mark.anyio +async def test_the_assistant_places_the_dubbed_voice_on_the_timeline(project, tmp_path, monkeypatch): + runner, store, pid, session, turn, _, after = await dubbed(project, tmp_path, monkeypatch) + job = job_of(after, turn) + voice = next(r for r in after.results if r.jobId == job.id and r.role == 'audio_track') + picture = next(a for a in after.assets if a.id == job.asset.assetId) + document = uuid4() + + business = AgentTools(store, runner, ModelConfigs(tmp_path)) + receipt = await business.execute( + pid, turn, session, 'call-2', 'execute_command', + {'type': 'editor.create', + 'payload': {'document': { + 'id': str(document), 'projectId': str(pid), 'kind': 'timeline', + 'data': {'width': 160, 'height': 120, 'fps': 24, 'tracks': [ + {'id': 'visual', 'title': 'Picture', 'kind': 'visual', + 'clips': [{'id': 'picture', 'inPoint': 0, 'outPoint': 5, + 'resource': {'asset': asset_ref(picture), 'title': 'Dubbed', 'durationSeconds': 5}}]}, + {'id': 'voice', 'title': 'Dubbed voice', 'kind': 'audio', + 'clips': [{'id': 'voice', 'start': 0, 'inPoint': 0, 'outPoint': 0.3, + 'resource': {'asset': asset_ref(next(a for a in after.assets if a.id == voice.asset.assetId)), + 'title': 'Dubbed voice', 'durationSeconds': 0.3}}]}]}}}}, + [], None) + + assert receipt['status'] == 'applied', receipt + timeline = next(d for d in store.snapshot(pid).editorDocuments if d.id == document) + assert [track.kind for track in timeline.data.tracks] == ['visual', 'audio'] + assert timeline.data.tracks[1].clips[0].resource.asset.assetId == voice.asset.assetId From a4d53a79494e4c10821cbdb199098a683a4ef9f1 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 14:17:45 +0800 Subject: [PATCH 31/58] [feat] models: keep the provider object-storage account with the account MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary Ark can only read media from an address it can fetch itself, so 翻配, 视频参考 and 按字幕配音 all need the same thing first: the source media in object storage the user owns, handed over as a signed URL. The store already reads `storage` from a resolved model configuration, but nothing wrote it, so every dubbing call died on `seed_audio_storage` before any request went out. This adds the missing owner without inventing a second place for credentials: - `ModelConfigs` keeps `storage` (`accessKey`, `secretKey`, `bucket`, `region`) on the account layer next to the API key, so one Ark service and one bucket serve every model under it. It is validated on read, hoisted into the shared service record on write, and carried across edits of any model in that account. - `storage()` answers Bucket, Region and whether the account is configured; neither secret is ever returned. `save_storage()` treats a blank field as "keep the stored value", so a settings screen never has to echo a secret back to change a bucket. - An incomplete account is refused as a whole instead of failing later inside an adapter. `#650` Tests: `tests/test_model_configs.py` (36 passed) covers sharing across one account, restart, secret masking, blank-field updates and refusal; `tests/test_seed_audio.py` (41 passed) covers dubbing going out with the presigned address, and refusing before any request when no account is configured. The credential contract is written down in `docs/architecture/unified-project.md`. --- docs/architecture/unified-project.md | 11 +++ .../infrastructure/model_configs.py | 47 ++++++++++++- tests/test_model_configs.py | 22 ++++++ tests/test_seed_audio.py | 69 +++++++++++++++++++ 4 files changed, 146 insertions(+), 3 deletions(-) diff --git a/docs/architecture/unified-project.md b/docs/architecture/unified-project.md index 14d9a18cc..03a1ffe53 100644 --- a/docs/architecture/unified-project.md +++ b/docs/architecture/unified-project.md @@ -116,6 +116,17 @@ Hiding a source display or its group does not change active references, structur 工程文件是权威数据。对象、文件、回执和变更记录通过明确的提交顺序与恢复机制协调;SQLite 可用于租约等运行协调。凭证不进入普通工程、公开回执或模型快照。 +#### 模型账号的对象存储 + +部分生成服务不接收本机文件,只能从它自己能拉取的地址读取素材。这类媒体必须先放入用户自己的对象存储,再把带签名的临时地址交给服务。凭证属于模型账号,不属于任何工程: + +- 存放在模型配置的账号层,与 API Key 同层,由该账号下的模型共享;不进入工程文件、公开回执、任务快照或执行记录。 +- 读取时只返回 Bucket、Region 和“是否已配置”,Access Key 与 Secret Key 不回传;更新时留空的字段沿用已存值。 +- 四个字段必须同时可用或同时不存在;缺失时在提交任何请求之前拒绝,并返回可本地化的错误码。 +- 交给服务的地址带有限期,同一素材在同一任务内复用同一地址,不重复上传。 + +这样翻配、视频参考和按字幕配音共用一条“先发布再生成”的路径,而不是每个适配器各自处理上传。 + UI、Agent 和后台完成写入共享可恢复变更通道。通知提示对象发生变化,查询返回权威状态;处理断线、重复和乱序,不能通过整页重载掩盖同步问题。 浏览器保存草稿、交互状态和可重建缓存。拖动中不逐指针写盘;按受影响对象更新,避免反复读取大媒体或全历史。冲突保留输入,视图保存失败与业务提交结果分别反馈。 diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index 9494704c4..d9f2e61da 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -16,6 +16,17 @@ from opendirector.infrastructure.local_projects import child, read_json, write_json MODEL_KINDS = ("agent", "image", "video", "audio", "vision") +STORAGE_KEYS = ("accessKey", "secretKey", "bucket", "region") + + +def storage_settings(storage, *, existing=None): + if not isinstance(storage, dict) or set(storage) - set(STORAGE_KEYS): + raise ProjectError("对象存储设置无效,请检查 Access Key、Secret Key、Bucket 和 Region。", 409) + merged = {**(existing or {}), **{key: value.strip() for key, value in storage.items() + if isinstance(value, str) and value.strip()}} + if set(merged) != set(STORAGE_KEYS): + raise ProjectError("对象存储需要同时填写 Access Key、Secret Key、Bucket 和 Region。", 409) + return merged class ModelConfigs: @@ -40,7 +51,7 @@ def _read(self) -> list[dict]: raise ValueError() services = value.get('services', {}) if not isinstance(services, dict) or any(not {'url', 'apiKey', 'connectionType', 'authMode'} <= set(service) - or set(service) - {'url', 'apiKey', 'connectionType', 'authMode', 'capabilityAutoCheck'} for service in services.values()): + or set(service) - {'url', 'apiKey', 'connectionType', 'authMode', 'capabilityAutoCheck', 'storage'} for service in services.values()): raise ValueError() for item in value['models']: if 'providerId' in item: @@ -48,11 +59,13 @@ 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'}: + 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'}: raise ValueError() if 'capabilityAutoCheck' in item and type(item['capabilityAutoCheck']) is not bool: raise ValueError() identifier(item["id"]) + if 'storage' in item: + storage_settings(item['storage']) if item["id"] in seen or item["kind"] not in MODEL_KINDS: raise ValueError() seen.add(item["id"]) @@ -133,6 +146,8 @@ def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str item['inputModalities'] = agent_input_modalities(kind, input_modalities if input_modalities is not None else (existing or {}).get('inputModalities')) item['videoAdapter'] = video_adapter if video_adapter is not None else (existing or {}).get('videoAdapter', 'auto') raw = video_capabilities if capabilities_supplied or video_capabilities is not None else (existing or {}).get('videoCapabilities') + if existing and 'storage' in existing: + item['storage'] = existing['storage'] item['videoCapabilities'] = check_video_config(kind, connection['protocol'], item['videoAdapter'], raw) profile = input_rules(item)['profile'] if item['videoCapabilities'] is not None and profile in {'fasth3-omni', 'vllm-omni-h3'}: @@ -146,11 +161,36 @@ def save(self, kind: str, url: str, model_id: str, api_key: str, config_id: str for peer in models: if peer.get('providerId') == item['providerId']: peer.update({key: item[key] for key in ('url', 'apiKey', 'connectionType', 'authMode', 'proxyMode')}) + if 'storage' in item: + peer['storage'] = item['storage'] if auto_check is not None: peer['capabilityAutoCheck'] = auto_check self._write(models) return self._public(item) + def storage(self, config_id: str) -> dict: + with self.lock: + item = next((item for item in self._read() if item["id"] == config_id), None) + if item is None: + raise ProjectError("模型配置已被删除,请重新加载。", 404) + values = item.get("storage") or {} + return {'bucket': values.get('bucket'), 'region': values.get('region'), + 'configured': set(values) == set(STORAGE_KEYS)} + + def save_storage(self, config_id: str, storage: dict) -> dict: + with self.lock: + models = self._read() + existing = next((item for item in models if item["id"] == config_id), None) + if existing is None: + raise ProjectError("模型配置已被删除,请重新加载。", 404) + values = storage_settings(storage, existing=existing.get('storage')) + provider = existing.get('providerId') + for item in models: + if item is existing or (provider and item.get('providerId') == provider): + item['storage'] = dict(values) + self._write(models) + return {'bucket': values['bucket'], 'region': values['region'], 'configured': True} + def delete(self, config_id: str) -> None: with self.lock: models = self._read() @@ -165,7 +205,8 @@ def _write(self, models: list[dict]) -> None: for model in models: item = dict(model) if 'providerId' in item: - services[item['providerId']] = {key: item.pop(key) for key in ('url', 'apiKey', 'connectionType', 'authMode')} + keys = ('url', 'apiKey', 'connectionType', 'authMode') + (('storage',) if 'storage' in item else ()) + services[item['providerId']] = {key: item.pop(key) for key in keys} if 'capabilityAutoCheck' in item: services[item['providerId']]['capabilityAutoCheck'] = item.pop('capabilityAutoCheck') stored.append(item) diff --git a/tests/test_model_configs.py b/tests/test_model_configs.py index fc8d18dbb..5a6dc345e 100644 --- a/tests/test_model_configs.py +++ b/tests/test_model_configs.py @@ -484,3 +484,25 @@ def test_batch_video_cards_keep_distinct_adapter_and_output_settings(api): first, second = response.json() assert first['videoCapabilities']['outputs'][0]['resolution'] == '540P' assert second['videoCapabilities'] is None and second['inputRules']['profile'] == 'vllm-omni-h3' + + +def test_object_storage_belongs_to_the_provider_account(tmp_path): + configs = ModelConfigs(tmp_path) + saved = configs.save_many('audio', 'https://ark.example/api/v3', ['doubao-seed-audio-1-5-261128', 'seed-tts-2.0'], + 'test-secret', protocol='volcengine', auth_mode='bearer') + first = saved[0]['id'] + account = {'accessKey': 'ak-probe', 'secretKey': 'sk-probe', 'bucket': 'bucket-a', 'region': 'cn-beijing'} + assert configs.storage(first) == {'bucket': None, 'region': None, 'configured': False} + assert configs.save_storage(first, account) == {'bucket': 'bucket-a', 'region': 'cn-beijing', 'configured': True} + assert configs.resolve(saved[1]['id'], 'audio')['storage'] == account + assert 'ak-probe' not in json.dumps(configs.storage(first)) + configs.save('audio', 'https://ark.example/api/v3', 'doubao-seed-audio-1-5-261128', 'new-secret', first, + protocol='volcengine', auth_mode='bearer') + assert ModelConfigs(tmp_path).resolve(first, 'audio')['storage'] == account + assert configs.save_storage(first, {'secretKey': '', 'bucket': 'bucket-b'})['bucket'] == 'bucket-b' + assert configs.resolve(first, 'audio')['storage']['secretKey'] == 'sk-probe' + other = configs.save('image', 'https://image.example/v1', 'demo', 'test-secret') + with pytest.raises(ProjectError, match='同时填写'): + configs.save_storage(other['id'], {'bucket': 'bucket-a'}) + with pytest.raises(ProjectError, match='对象存储设置无效'): + configs.save_storage(other['id'], {'bucket': 'bucket-a', 'token': 'x'}) diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index 96e3f70ee..bd6dd7bb6 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -475,3 +475,72 @@ def test_separation_refuses_more_than_six_minutes_in_one_clip(tmp_path): with pytest.raises(ProjectError) as failure: generation_references(store, task, config()) assert failure.value.code == 'audio_reference_audio' + + +def seed_dubbing_ready(): + return {'prompt': '', 'images': [], 'audios': [], 'videos': [b'\0\0\0\x18ftypmp42'], 'manifest': [], + 'subtitle': None, 'continueFrom': None, 'continueSize': None, 'control': None, 'guides': [], + 'audio_role': 'reference_audio', 'rules': input_rules({**config(), 'kind': 'audio'})} + + +def seed_dubbing_task(): + return {'kind': 'audio', 'projectId': 'p', 'id': 'job', 'prompt': '', + 'parameters': {'taskType': 'dubbing', 'target_language': 'en', 'output_format': 'mp4'}} + + +def configured_storage(tmp_path, monkeypatch): + from opendirector.infrastructure.model_configs import ModelConfigs + from opendirector.integrations import volcengine as module + configs = ModelConfigs(tmp_path) + saved = configs.save('audio', CONTENT_BASE, MODEL, 'fixture-key', protocol='volcengine', auth_mode='bearer') + configs.save_storage(saved['id'], {'accessKey': 'ak', 'secretKey': 'sk', 'bucket': 'bucket-a', + 'region': 'cn-beijing'}) + uploaded = [] + monkeypatch.setattr(module, 'generation_references', lambda store, task, configuration: seed_dubbing_ready()) + monkeypatch.setattr(module.tos_transfer, 'put', lambda configuration, bucket, region, key, path, + access_key, secret_key, **kwargs: uploaded.append((bucket, key))) + monkeypatch.setattr(module.tos_transfer, 'presign', + lambda bucket, region, key, access_key, secret_key, expires=0: f'https://tos.example/{key}') + return configs.resolve(saved['id'], 'audio'), uploaded + + +@pytest.mark.anyio +async def test_a_configured_account_lets_the_service_fetch_the_video(tmp_path, monkeypatch): + dubbed = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', + 'sine=frequency=440:sample_rate=44100', '-t', '0.2', + '-threads', '1', '-f', 'mp3', 'pipe:1'], + capture_output=True, check=True).stdout + posted = [] + + def handler(request): + if request.method == 'GET': + return httpx.Response(200, content=dubbed, headers={'content-type': 'video/mp4'}) + posted.append(json.loads(request.content)) + return httpx.Response(200, json={'content': {'video_url': 'http://fixture.invalid/api/v3/dubbed.mp4', + 'audios': [{'url': 'http://fixture.invalid/api/v3/mix.mp3', 'type': 'composite'}]}}) + + account, uploaded = configured_storage(tmp_path, monkeypatch) + provider = VolcengineGeneration(None, transport=httpx.MockTransport(handler), poll_interval=0) + suffix, _ = await provider.generate(account, seed_dubbing_task(), lambda external_id: None) + assert suffix == 'mp4' + (bucket, key), = uploaded + assert bucket == 'bucket-a' and key.startswith('od/job/') and key.endswith('.mp4') + assert posted[0]['content'][0] == {'type': 'video_url', 'role': 'dubbing_video', + 'video_url': {'url': f'https://tos.example/{key}'}} + assert posted[0]['dubbing_config'] == {'target_language': 'en'} + + +@pytest.mark.anyio +async def test_dubbing_refuses_before_any_request_without_an_account(tmp_path, monkeypatch): + from opendirector.infrastructure.model_configs import ModelConfigs + from opendirector.integrations import volcengine as module + configs = ModelConfigs(tmp_path) + saved = configs.save('audio', CONTENT_BASE, MODEL, 'fixture-key', protocol='volcengine', auth_mode='bearer') + monkeypatch.setattr(module, 'generation_references', lambda store, task, configuration: seed_dubbing_ready()) + posted = [] + provider = VolcengineGeneration(None, transport=httpx.MockTransport( + lambda request: posted.append(request)), poll_interval=0) + with pytest.raises(ProjectError) as failure: + await provider.generate(configs.resolve(saved['id'], 'audio'), seed_dubbing_task(), lambda external_id: None) + assert failure.value.code == 'seed_audio_storage' + assert posted == [] From fbe72b5c3eba591153ea976bd68483e221886627 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 14:21:10 +0800 Subject: [PATCH 32/58] [feat] api: let a model service hold its object-storage credentials MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary The storage account added for remote-fetch providers had no way in from outside the process, so a user could not actually configure 翻配 or 视频参考. Two endpoints on the existing model-service resource close that: `GET /api/model-services/{id}/storage` reports the bucket, region and whether the account is usable, `POST` stores the four credentials. Neither secret comes back: the response is a separate public shape with no key fields at all, and the saved account is shared by every model of the same provider service. A blank field keeps the stored value, so changing a bucket never requires re-entering the secret, and an account with only some of the four fields is refused up front. The two refusals carry stable codes (`model_storage_incomplete`, `model_storage_invalid`) registered in the contract issue codes and the English catalog, so the interface answers them in its own language instead of echoing Chinese. `#650` Tests: `tests/test_model_configs.py` (37 passed) covers the read before any account exists, saving, masking, blank-field updates, the 409 refusal in both languages and the 404 for a deleted service; `tests/test_creation_contracts.py` (82 passed) regenerates and checks the new contract shapes. --- apps/api/src/opendirector_api/localization.py | 2 + apps/api/src/opendirector_api/main.py | 10 +- apps/api/src/opendirector_api/models.py | 2 +- .../opendirector/domain/creation/commands.py | 2 +- .../opendirector/domain/creation/models.py | 13 ++ .../infrastructure/model_configs.py | 6 +- src/contracts/creation.schema.json | 168 +++++++++++++++++- src/contracts/generated.ts | 30 +++- tests/test_model_configs.py | 21 +++ 9 files changed, 245 insertions(+), 9 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index c198291d5..bcccc19d4 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -20,6 +20,8 @@ from opendirector.domain.creation.assets import ASSET_DOWNLOAD_ENGLISH ENGLISH_BY_CODE = { + 'model_storage_invalid': 'The object storage settings are not valid. Check the access key, secret key, bucket and region.', + 'model_storage_incomplete': 'Object storage needs an access key, secret key, bucket and region. Fill in all four or leave them empty.', 'video_compression_preset': 'Choose a valid compression preset.', 'video_compression_source': 'Select one video to compress.', **ASSET_DOWNLOAD_ENGLISH, diff --git a/apps/api/src/opendirector_api/main.py b/apps/api/src/opendirector_api/main.py index 1a5d95024..7a2906548 100644 --- a/apps/api/src/opendirector_api/main.py +++ b/apps/api/src/opendirector_api/main.py @@ -40,7 +40,7 @@ from opendirector_api.models import (ModelConfigInput, ModelConfigPublic, AgentModelTest, ModelCapabilityRequest, ModelDiscoveryRequest, ModelBatchInput, ToolTaskCreate, ToolPlacement, ImageSelectionCreate, AvailabilityRefresh, AvailabilityCatalog, - ModelAvailability as ModelAvailabilityResponse) + ModelAvailability as ModelAvailabilityResponse, ModelStorage, ModelStoragePublic) async def _cli_prompt_rewrite(runtime, model, thinking, messages): @@ -262,6 +262,14 @@ def get_settings(): def update_settings(value: GeneralSettingsPatch): return preferences.update(value.model_dump()) + @app.get('/api/model-services/{config_id}/storage', response_model=ModelStoragePublic) + def read_model_storage(config_id: UUID): + return model_configs.storage(str(config_id)) + + @app.post('/api/model-services/{config_id}/storage', response_model=ModelStoragePublic) + def save_model_storage(config_id: UUID, value: ModelStorage): + return model_configs.save_storage(str(config_id), value.model_dump()) + @app.delete('/api/model-services/{config_id}', status_code=204) def delete_model_service(config_id: UUID): catalog.delete_service(str(config_id)) diff --git a/apps/api/src/opendirector_api/models.py b/apps/api/src/opendirector_api/models.py index a095e33f5..3e17099e8 100644 --- a/apps/api/src/opendirector_api/models.py +++ b/apps/api/src/opendirector_api/models.py @@ -5,7 +5,7 @@ from opendirector.domain.creation.editors import ToolDraftBinding from opendirector.domain.capabilities import AgentInputModality from opendirector.domain.video_capabilities import VideoAdapter, VideoCapabilities -from opendirector.domain.creation.models import ModelAvailability, AvailabilityCatalog +from opendirector.domain.creation.models import ModelAvailability, AvailabilityCatalog, ModelStorage, ModelStoragePublic class Model(BaseModel): diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 680a05455..ea3edabc1 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -618,7 +618,7 @@ def command_fingerprint(command: Command) -> str: 'voice_not_found', 'voice_delete_unsupported', 'voice_consent_required', 'voice_name_invalid', 'voice_audio_invalid', 'voice_format', 'voice_size', 'voice_duration', 'voice_provider_protocol', 'voice_provider_error', 'voice_provider_timeout', 'voice_model_unsupported', - 'voice_name_taken', 'voice_provider_quota'] + 'voice_name_taken', 'voice_provider_quota', 'model_storage_invalid', 'model_storage_incomplete'] class ContractIssue(Contract): diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index 5146fc75d..cd2366fed 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -116,6 +116,19 @@ def consistent(self): return self +class ModelStorage(Contract): + accessKey: str = Field(default='', max_length=512, description='Object-storage access key ID; blank keeps the stored one.') + secretKey: str = Field(default='', max_length=512, description='Object-storage secret access key; blank keeps the stored one.') + bucket: str = Field(default='', max_length=200, description='Bucket the provider may read generated media from.') + region: str = Field(default='', max_length=100, description='Object-storage region of that bucket.') + + +class ModelStoragePublic(Contract): + bucket: str | None = Field(default=None, description='Stored bucket, or null when no account is configured.') + region: str | None = Field(default=None, description='Stored region, or null when no account is configured.') + configured: bool = Field(description='Whether the provider account can publish media for remote fetch.') + + class ModelConnection(Contract): kind: ModelKind = Field(description='Business object or media type.') url: str = Field(min_length=1, max_length=2048, description='Provider API base URL.') diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index d9f2e61da..0086b8498 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -21,11 +21,13 @@ def storage_settings(storage, *, existing=None): if not isinstance(storage, dict) or set(storage) - set(STORAGE_KEYS): - raise ProjectError("对象存储设置无效,请检查 Access Key、Secret Key、Bucket 和 Region。", 409) + raise ProjectError("对象存储设置无效,请检查 Access Key、Secret Key、Bucket 和 Region。", 409, + code="model_storage_invalid") merged = {**(existing or {}), **{key: value.strip() for key, value in storage.items() if isinstance(value, str) and value.strip()}} if set(merged) != set(STORAGE_KEYS): - raise ProjectError("对象存储需要同时填写 Access Key、Secret Key、Bucket 和 Region。", 409) + raise ProjectError("对象存储需要同时填写 Access Key、Secret Key、Bucket 和 Region。", 409, + code="model_storage_incomplete") return merged diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 40df62ed1..43ff2231d 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4829,7 +4829,9 @@ "voice_provider_timeout", "voice_model_unsupported", "voice_name_taken", - "voice_provider_quota" + "voice_provider_quota", + "model_storage_invalid", + "model_storage_incomplete" ], "title": "Code", "type": "string" @@ -10978,6 +10980,82 @@ "title": "ModelSnapshot", "type": "object" }, + "ModelStorage": { + "additionalProperties": false, + "properties": { + "accessKey": { + "default": "", + "description": "Object-storage access key ID; blank keeps the stored one.", + "maxLength": 512, + "title": "Accesskey", + "type": "string" + }, + "secretKey": { + "default": "", + "description": "Object-storage secret access key; blank keeps the stored one.", + "maxLength": 512, + "title": "Secretkey", + "type": "string" + }, + "bucket": { + "default": "", + "description": "Bucket the provider may read generated media from.", + "maxLength": 200, + "title": "Bucket", + "type": "string" + }, + "region": { + "default": "", + "description": "Object-storage region of that bucket.", + "maxLength": 100, + "title": "Region", + "type": "string" + } + }, + "title": "ModelStorage", + "type": "object" + }, + "ModelStoragePublic": { + "additionalProperties": false, + "properties": { + "bucket": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored bucket, or null when no account is configured.", + "title": "Bucket" + }, + "region": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored region, or null when no account is configured.", + "title": "Region" + }, + "configured": { + "description": "Whether the provider account can publish media for remote fetch.", + "title": "Configured", + "type": "boolean" + } + }, + "required": [ + "configured" + ], + "title": "ModelStoragePublic", + "type": "object" + }, "MotionCanvasItem": { "additionalProperties": false, "properties": { @@ -25151,7 +25229,9 @@ "voice_provider_timeout", "voice_model_unsupported", "voice_name_taken", - "voice_provider_quota" + "voice_provider_quota", + "model_storage_invalid", + "model_storage_incomplete" ], "title": "Code", "type": "string" @@ -31517,6 +31597,90 @@ "title": "ModelSnapshot", "type": "object" }, + "ModelStorage": { + "additionalProperties": false, + "properties": { + "accessKey": { + "default": "", + "description": "Object-storage access key ID; blank keeps the stored one.", + "maxLength": 512, + "title": "Accesskey", + "type": "string" + }, + "secretKey": { + "default": "", + "description": "Object-storage secret access key; blank keeps the stored one.", + "maxLength": 512, + "title": "Secretkey", + "type": "string" + }, + "bucket": { + "default": "", + "description": "Bucket the provider may read generated media from.", + "maxLength": 200, + "title": "Bucket", + "type": "string" + }, + "region": { + "default": "", + "description": "Object-storage region of that bucket.", + "maxLength": 100, + "title": "Region", + "type": "string" + } + }, + "required": [ + "accessKey", + "secretKey", + "bucket", + "region" + ], + "title": "ModelStorage", + "type": "object" + }, + "ModelStoragePublic": { + "additionalProperties": false, + "properties": { + "bucket": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored bucket, or null when no account is configured.", + "title": "Bucket" + }, + "region": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Stored region, or null when no account is configured.", + "title": "Region" + }, + "configured": { + "description": "Whether the provider account can publish media for remote fetch.", + "title": "Configured", + "type": "boolean" + } + }, + "required": [ + "bucket", + "region", + "configured" + ], + "title": "ModelStoragePublic", + "type": "object" + }, "MotionCanvasItem": { "additionalProperties": false, "properties": { diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 2c87584f3..05ecbc556 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -513,7 +513,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -1059,6 +1059,19 @@ export interface ModelSnapshotInput extends ContractInput { readonly inputRules?: InputRulesInput | null; } +export interface ModelStorageInput extends ContractInput { + readonly accessKey?: string; + readonly secretKey?: string; + readonly bucket?: string; + readonly region?: string; +} + +export interface ModelStoragePublicInput extends ContractInput { + readonly bucket?: string | null; + readonly region?: string | null; + readonly configured: boolean; +} + export interface MotionCanvasItemInput extends EditorCanvasItemInput { readonly kind: "motion"; } @@ -2573,7 +2586,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId: string | null; readonly field: string | null; @@ -3118,6 +3131,19 @@ export interface ModelSnapshot extends Contract { readonly inputRules: InputRules | null; } +export interface ModelStorage extends Contract { + readonly accessKey: string; + readonly secretKey: string; + readonly bucket: string; + readonly region: string; +} + +export interface ModelStoragePublic extends Contract { + readonly bucket: string | null; + readonly region: string | null; + readonly configured: boolean; +} + export interface MotionCanvasItem extends EditorCanvasItem { readonly kind: "motion"; } diff --git a/tests/test_model_configs.py b/tests/test_model_configs.py index 5a6dc345e..cdefff969 100644 --- a/tests/test_model_configs.py +++ b/tests/test_model_configs.py @@ -506,3 +506,24 @@ def test_object_storage_belongs_to_the_provider_account(tmp_path): configs.save_storage(other['id'], {'bucket': 'bucket-a'}) with pytest.raises(ProjectError, match='对象存储设置无效'): configs.save_storage(other['id'], {'bucket': 'bucket-a', 'token': 'x'}) + + +def test_storage_settings_are_configured_through_the_api(api): + client, _ = api + created = client.post('/api/model-configs', json=payload('audio')).json() + path = f"/api/model-services/{created['id']}/storage" + assert client.get(path).json() == {'bucket': None, 'region': None, 'configured': False} + saved = client.post(path, json={'accessKey': 'ak-probe', 'secretKey': 'sk-probe', + 'bucket': 'bucket-a', 'region': 'cn-beijing'}) + assert saved.status_code == 200 + assert saved.json() == {'bucket': 'bucket-a', 'region': 'cn-beijing', 'configured': True} + assert 'sk-probe' not in saved.text and 'ak-probe' not in saved.text + assert client.get(path).json()['configured'] is True + assert client.post(path, json={'bucket': ''}).json()['bucket'] == 'bucket-a' + fresh = client.post('/api/model-configs', json=payload('image')).json() + refused = client.post(f"/api/model-services/{fresh['id']}/storage", json={'bucket': 'bucket-a'}) + assert refused.status_code == 409 and refused.json()['code'] == 'model_storage_incomplete' + english = client.post(f"/api/model-services/{fresh['id']}/storage", json={'bucket': 'bucket-a'}, + headers={'accept-language': 'en-US'}) + assert english.json()['detail'].startswith('Object storage needs an access key') + assert client.post(f"/api/model-services/{uuid4()}/storage", json={}).status_code == 404 From b5b49785be546bca490ba39960f1dbd1f3f4cf3b Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:13:35 +0800 Subject: [PATCH 33/58] [refactor] audio: publish provider media through one helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary Ark can only read what it can fetch itself, so every request that carries a file has to put it in the user's bucket first and hand over a signed address. Dubbing did that inline for its video and, once subtitles arrived, a second nearly identical block grew inside the same branch — two copies of put, presign, cleanup and error mapping that the reference and subtitle paths would each have had to repeat. `_publish_media(config, task_id, data, suffix, content_type, noun=...)` now owns that step: it refuses before writing anything when the account is unconfigured, writes the bytes to a temporary file, uploads, presigns for an hour and always removes the temp file. Dubbing calls it for the video and for the subtitle, so the behaviour is the one already covered by the existing dubbing and subtitle tests, not a new one. The noun stays a parameter so a failure still says which file could not be published; the error code keeps coming from the transfer so the interface can answer in its own language. `#650` Tests: `tests/test_seed_audio.py` + `tests/test_result_artifacts.py` 53 passed, including the dubbing body carrying the presigned video URL and the subtitle travelling with it. --- .../opendirector/integrations/volcengine.py | 60 ++++++++----------- 1 file changed, 25 insertions(+), 35 deletions(-) diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index eb2f990a0..35950f656 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -238,45 +238,14 @@ async def query(): raise protocol_failure(stage) await asyncio.sleep(self.poll_interval) if kind == "audio" and is_seed_audio(config["modelId"]) and task["parameters"].get("taskType") == "dubbing": - storage = config.get("storage") or {} if not prepared["videos"]: raise ProjectError("翻配需要引用一段视频。", 422, code="audio_reference_video") - if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): - raise ProjectError("翻配需要先配置对象存储,方舟只能拉取可访问的地址。", 422, - code="seed_audio_storage") - key = f"od/{task['id']}/{uuid4()}.mp4" - media = prepared["videos"][0] - path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.mp4") - with open(path, "wb") as handle: - handle.write(media) - try: - await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], - key, path, storage["accessKey"], storage["secretKey"], - content_type="video/mp4") - except tos_transfer.TransferError as error: - raise ProjectError("视频上传失败,请检查对象存储配置后重试。", 502, - code=f"seed_audio_{error.code}") from error - finally: - os.unlink(path) - source = tos_transfer.presign(storage["bucket"], storage["region"], key, - storage["accessKey"], storage["secretKey"], expires=3600) + source = await self._publish_media(config, task["id"], prepared["videos"][0], "mp4", "video/mp4", + noun="视频") subtitle_url = None if prepared.get("subtitle"): - subtitle_key = f"od/{task['id']}/{uuid4()}.srt" - subtitle_path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.srt") - with open(subtitle_path, "wb") as handle: - handle.write(prepared["subtitle"]) - try: - await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], - subtitle_key, subtitle_path, storage["accessKey"], - storage["secretKey"], content_type="application/x-subrip") - except tos_transfer.TransferError as error: - raise ProjectError("字幕上传失败,请检查对象存储配置后重试。", 502, - code=f"seed_audio_{error.code}") from error - finally: - os.unlink(subtitle_path) - subtitle_url = tos_transfer.presign(storage["bucket"], storage["region"], subtitle_key, - storage["accessKey"], storage["secretKey"], expires=3600) + subtitle_url = await self._publish_media(config, task["id"], prepared["subtitle"], "srt", + "application/x-subrip", noun="字幕") payload = seed_audio_dubbing_body(config, source, task["parameters"], subtitle_url) stage = 'submit' async with client.stream("POST", endpoint(config["url"], "/contents/generations"), @@ -337,6 +306,27 @@ async def query(): except (ValueError, TypeError, KeyError, IndexError, AttributeError): raise protocol_failure(stage) from None + async def _publish_media(self, config, task_id, data, suffix, content_type, *, noun="素材"): + """Put one file where the provider can fetch it and return an address it may read.""" + storage = config.get("storage") or {} + if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): + raise ProjectError("该任务需要先配置对象存储,方舟只能拉取可访问的地址。", 422, + code="seed_audio_storage") + key = f"od/{task_id}/{uuid4()}.{suffix}" + path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.{suffix}") + with open(path, "wb") as handle: + handle.write(data) + try: + await asyncio.to_thread(tos_transfer.put, config, storage["bucket"], storage["region"], key, path, + storage["accessKey"], storage["secretKey"], content_type=content_type) + except tos_transfer.TransferError as error: + raise ProjectError(f"{noun}上传失败,请检查对象存储配置后重试。", 502, + code=f"seed_audio_{error.code}") from error + finally: + os.unlink(path) + return tos_transfer.presign(storage["bucket"], storage["region"], key, + storage["accessKey"], storage["secretKey"], expires=3600) + async def _download(self, client, url, *, secrets=(), public_only=False): parts = urlsplit(url) if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username or parts.password: From a521923066a75e64ee810230d1794b8061a1aebd Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:16:09 +0800 Subject: [PATCH 34/58] [refactor] audio: decide storage readiness in one place ## summary Two call sites now need the same yes/no answer about the provider account: the upload helper itself, and the subtitle path, which has to tell "this job has a subtitle and nothing to publish it with" apart from a plain missing account before it calls the helper. Keeping the four-field test in both places would let them drift, and a drifting readiness check shows up as a wrong error code rather than a test failure. `_storage_ready(config)` holds it once and `_publish_media` asks it, so the subtitle path and the helper can never disagree about whether the same account is usable. It stays on the Ark adapter: object storage is a property of a provider that only reads remote URLs, not of every generation provider, and the base class has no other reason to know about buckets. `#650` Tests: `tests/test_seed_audio.py` + `tests/test_result_artifacts.py` 53 passed, including dubbing refused with `seed_audio_storage` before any request when no account is configured, and publishing the video and subtitle when one is. --- .../core/src/opendirector/integrations/volcengine.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index 35950f656..24fb64959 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -306,12 +306,15 @@ async def query(): except (ValueError, TypeError, KeyError, IndexError, AttributeError): raise protocol_failure(stage) from None - async def _publish_media(self, config, task_id, data, suffix, content_type, *, noun="素材"): - """Put one file where the provider can fetch it and return an address it may read.""" + def _storage_ready(self, config): storage = config.get("storage") or {} - if not all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")): + return all(storage.get(key) for key in ("accessKey", "secretKey", "bucket", "region")) + + async def _publish_media(self, config, task_id, data, suffix, content_type, *, noun="素材"): + if not self._storage_ready(config): raise ProjectError("该任务需要先配置对象存储,方舟只能拉取可访问的地址。", 422, code="seed_audio_storage") + storage = config["storage"] key = f"od/{task_id}/{uuid4()}.{suffix}" path = os.path.join(tempfile.gettempdir(), f"{uuid4()}.{suffix}") with open(path, "wb") as handle: From 018e0f57fa23cc0a209871bbf4bc2bf782122d32 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:30:57 +0800 Subject: [PATCH 35/58] [feat] assets: upload a subtitle file as a subtitle asset MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary 按字幕配音 needs an uploaded SRT, but the upload inspector only recognised `.txt` and `.md` as text. An `.srt` fell through to the media branch and came back as a generic file, so no subtitle asset could ever exist and `subtitleAssetId` was unreachable from the interface — the validation in the audio reference layer was correct and simply could never be satisfied. `.srt` now inspects as text with `application/x-subrip`, which is the type the reference layer already accepts. The size and UTF-8 checks are the existing text ones; a subtitle that is not valid SRT timings is still refused later, by the rule that owns that judgement. `#650` Tests: `tests/test_creation_assets.py::test_an_srt_upload_becomes_a_subtitle_asset` uploads a real SRT through the API and reads the bytes back; `tests/test_seed_audio.py` now asserts the reference layer accepts both `text/plain` and `application/x-subrip` subtitles. That test failed with `kind == 'file'` before `.srt` was recognised. 235 passed across the seven modules touched by this branch. --- .../src/opendirector/infrastructure/creation_uploads.py | 5 +++-- tests/test_creation_assets.py | 8 ++++++++ 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/packages/core/src/opendirector/infrastructure/creation_uploads.py b/packages/core/src/opendirector/infrastructure/creation_uploads.py index eead9a10f..88c34ab5e 100644 --- a/packages/core/src/opendirector/infrastructure/creation_uploads.py +++ b/packages/core/src/opendirector/infrastructure/creation_uploads.py @@ -59,7 +59,7 @@ def inspect_file(path: Path, name: str, *, expected_kind=None): if suffix in {'.ttf', '.otf', '.ttc', '.otc', '.woff', '.woff2'} or prefix[:4] in FONT_SIGNATURES: font = inspect_font(path) return 'file', MediaMetadata(size=size, mimeType=font.mimeType) - if suffix in {'.txt', '.md'} or expected_kind == 'text': + if suffix in {'.txt', '.md', '.srt'} or expected_kind == 'text': if size > MAX_CREATION_TEXT_BYTES: raise ProjectError('文本素材应不超过 1 MiB。', 413) try: @@ -68,7 +68,8 @@ def inspect_file(path: Path, name: str, *, expected_kind=None): raise ProjectError('文本素材需使用 UTF-8 编码。') from None if any(ord(char) < 32 and char not in '\t\r\n' for char in text): raise ProjectError('文件包含非文本内容,请导入 UTF-8 文本。') - return 'text', MediaMetadata(size=size, mimeType='text/markdown' if suffix == '.md' else 'text/plain') + mime = {'md': 'text/markdown', 'srt': 'application/x-subrip'}.get(suffix.lstrip('.'), 'text/plain') + return 'text', MediaMetadata(size=size, mimeType=mime) with path.open('rb') as stream: prefix = stream.read(16) image_bytes = (prefix.startswith((b'\x89PNG\r\n\x1a\n', b'\xff\xd8\xff', b'GIF87a', b'GIF89a')) diff --git a/tests/test_creation_assets.py b/tests/test_creation_assets.py index 03228966e..013cc5707 100644 --- a/tests/test_creation_assets.py +++ b/tests/test_creation_assets.py @@ -579,6 +579,14 @@ def test_empty_text_and_generic_files_have_safe_content_access(api): assert response.headers['content-disposition'].startswith('attachment;') +def test_an_srt_upload_becomes_a_subtitle_asset(api): + client, base, _, project_id = api + lines = '1\n00:00:00,000 --> 00:00:02,000\n你好\n\n'.encode() + info, _, asset_id = api_upload(client, base, data=lines, name='lines.srt') + assert info['kind'] == 'text' and info['metadata']['mimeType'] == 'application/x-subrip' + assert client.get(base + '/assets/' + asset_id + '/content').content == lines + + def test_clipboard_image_without_suffix_is_inspected_from_its_bytes(api): client, base, _, _ = api info, _, asset_id = api_upload(client, base, name='clipboard') From 23d069bc14e378ae96d7491aba6b84b8146c9419 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:33:13 +0800 Subject: [PATCH 36/58] [feat] audio: accept the four reference shapes Seed Audio allows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary The provider takes exactly four reference combinations: one image, one video, up to six voice clips, or one video with voice clips. The adapter only ever implemented the first and third. A video fell into the "not supported" branch unless the task was dubbing, and voice clips were refused next to a video, so 视频参考生音频 and 音视频参考生音频 could not be requested at all — both are in the acceptance list for `#650`. Video is now a reference like any other. Dubbing keeps its own role `dubbing_video` and its MP4-only bound; every other task sends `reference_video` and accepts MP4 or MOV. Because the service can only fetch video from a URL, a reference video goes through the same `_publish_media` path as the dubbing source, and the declared content type follows the container brand instead of assuming MP4. The mix rule now states the real constraint: image cannot be combined with video or voice, and dubbing cannot carry voice clips. Image plus voice stays refused, as before. Three codes were added so each refusal keeps its own meaning in both languages: `audio_dubbing_video` (wrong format or length for dubbing), `audio_dubbing_source` (no source video), `audio_separation_video` (separation takes audio only). `audio_reference_video` now only means a video the service cannot accept, and `audio_reference_count` and `audio_reference_mix` were reworded to describe the wider matrix. `#650` Tests: `tests/test_seed_audio.py` covers a video travelling as `reference_video`, a video with a voice clip travelling together, the image-plus-video and separation-plus-video refusals, the declared type for both container brands, and a published video arriving in the request body. The publish test fails with an empty publish list before the adapter change. `tests/test_localization.py` answers each new code in English and Chinese. 236 passed across the seven modules touched by this branch. --- apps/api/src/opendirector_api/localization.py | 9 +- .../opendirector/domain/creation/commands.py | 2 +- .../integrations/reference_inputs.py | 25 +++-- .../opendirector/integrations/seed_audio.py | 8 +- .../opendirector/integrations/volcengine.py | 13 ++- src/contracts/creation.schema.json | 6 ++ src/contracts/generated.ts | 4 +- tests/test_localization.py | 15 +++ tests/test_seed_audio.py | 101 ++++++++++++++++-- 9 files changed, 157 insertions(+), 26 deletions(-) diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index bcccc19d4..4a2c55321 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -65,9 +65,12 @@ 'seed_audio_base_url': 'Seed Audio 1.5 needs the Ark content-generation base URL ending in /api/v3. Add the Seed Audio preset instead.', 'audio_reference_image': 'That reference cannot be sent: Seed Audio takes PNG, JPEG or WEBP images within the size limit.', 'audio_reference_audio': 'Voice references must be WAV or MP3 and 2 to 30 seconds long.', - 'audio_reference_count': 'Seed Audio takes at most one image or six voice references, up to 180 seconds in total.', - 'audio_reference_mix': 'Seed Audio cannot combine an image reference with voice references.', - 'audio_reference_video': 'This Seed Audio adapter does not accept video references yet.', + 'audio_reference_count': 'Seed Audio takes at most one image, one video, or six voice references up to 180 seconds in total.', + 'audio_reference_mix': 'Seed Audio cannot combine these inputs: send one image, one video with optional voice clips, or voice clips alone.', + 'audio_reference_video': 'A video reference must be MP4 or MOV, 4 seconds to 6 minutes.', + 'audio_dubbing_video': 'A dubbing source must be an MP4 clip of 4 seconds to 6 minutes.', + 'audio_dubbing_source': 'Dubbing needs a source video to re-voice.', + 'audio_separation_video': 'Track separation takes one audio input and no video.', 'audio_subtitle_scope': 'A subtitle file is used only when dubbing a referenced video.', 'audio_subtitle_asset': 'The subtitle must be an SRT file within the size limit.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', diff --git a/packages/core/src/opendirector/domain/creation/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index ea3edabc1..f2f8d1910 100644 --- a/packages/core/src/opendirector/domain/creation/commands.py +++ b/packages/core/src/opendirector/domain/creation/commands.py @@ -606,7 +606,7 @@ def command_fingerprint(command: Command) -> str: 'capability_unsupported', 'preview_expired', 'storage_unavailable', 'submission_unknown', 'provider_error', 'audio_music_unsupported', 'audio_mode_required', 'audio_task_unsupported', 'seed_audio_base_url', 'audio_reference_image', 'audio_reference_audio', 'audio_reference_count', 'audio_reference_mix', - 'audio_reference_video', 'audio_subtitle_scope', 'audio_subtitle_asset', 'seed_audio_storage', 'seed_audio_storage_rejected', 'seed_audio_storage_timeout', 'seed_audio_storage_unreachable', + 'audio_reference_video', 'audio_dubbing_video', 'audio_dubbing_source', 'audio_separation_video', 'audio_subtitle_scope', 'audio_subtitle_asset', 'seed_audio_storage', 'seed_audio_storage_rejected', 'seed_audio_storage_timeout', 'seed_audio_storage_unreachable', 'moss_speech_text', 'moss_speech_voice', 'moss_speech_reference', 'moss_prompt_limit', 'moss_image_size', 'moss_image_reference', 'moss_layout_reference', 'bigmodel_image_size', 'bigmodel_image_reference', 'bigmodel_image_prompt', diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 5018f3682..4d76bf8b2 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -114,17 +114,22 @@ def seed_audio_references(store, task, rules, result, overrides): raise ProjectError(f'参考音频最多 {rules["maxAudios"]} 段、合计不超过 {budget_ms // 1000} 秒。', 422, code='audio_reference_count') result['audios'].append(data_uri(data, 'audio/wav' if meta['type'] == 'audio/x-wav' else meta['type'])) result['manifest'].append({**entry, 'role': result['audio_role']}) - elif source_kind == 'video' and dubbing: + elif source_kind == 'video': + if separating: + raise ProjectError('分轨只接收一段音频,不支持视频。', 422, code='audio_separation_video') duration = meta.get('durationMs') low, high = SEED_AUDIO_DUBBING_MS - if meta.get('type') not in {'video/mp4'} or duration is None or not low <= duration <= high: - raise ProjectError('翻配视频需为 MP4,时长 4 秒至 6 分钟。', 422, code='audio_reference_video') - if result['videos']: - raise ProjectError('翻配一次只能引用一段视频。', 422, code='audio_reference_count') + accepted = {'video/mp4'} if dubbing else {'video/mp4', 'video/quicktime'} + if meta.get('type') not in accepted or duration is None or not low <= duration <= high: + if dubbing: + raise ProjectError('翻配视频需为 MP4,时长 4 秒至 6 分钟。', 422, code='audio_dubbing_video') + raise ProjectError('参考视频需为 MP4 或 MOV,时长 4 秒至 6 分钟。', 422, code='audio_reference_video') + if len(result['videos']) >= rules['maxVideos']: + raise ProjectError('Seed Audio 1.5 一次只能引用一段视频。', 422, code='audio_reference_count') result['videos'].append(data) - result['manifest'].append({**entry, 'role': 'dubbing_video'}) + result['manifest'].append({**entry, 'role': 'dubbing_video' if dubbing else 'reference_video'}) else: - raise ProjectError(f'“{meta["name"]}”:Seed Audio 1.5 暂不接受视频参考。', 422, code='audio_reference_video') + raise ProjectError(f'“{meta["name"]}”:Seed Audio 1.5 不接受这个素材。', 422, code='audio_reference_mix') subtitle_id = (task.get('parameters') or {}).get('subtitleAssetId') if subtitle_id: if not dubbing or not result['videos']: @@ -137,8 +142,10 @@ def seed_audio_references(store, task, rules, result, overrides): result['subtitle'] = data result['manifest'].append({'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': 'text', 'transmission': 'content', 'role': 'custom_subtitle'}) - if result['videos'] and (result['images'] or result['audios']): - raise ProjectError('翻配视频不能与图片或音频参考同时使用。', 422, code='audio_reference_mix') + if result['videos'] and result['images']: + raise ProjectError('Seed Audio 1.5 的视频参考与图片参考不能同时使用。', 422, code='audio_reference_mix') + if dubbing and result['audios']: + raise ProjectError('翻配视频不能再搭配音频参考,请改用普通音频参考生成。', 422, code='audio_reference_mix') if result['images'] and result['audios']: raise ProjectError('Seed Audio 1.5 的图片参考与音频参考不能同时使用。', 422, code='audio_reference_mix') return result diff --git a/packages/core/src/opendirector/integrations/seed_audio.py b/packages/core/src/opendirector/integrations/seed_audio.py index 642b533cf..a6fb76151 100644 --- a/packages/core/src/opendirector/integrations/seed_audio.py +++ b/packages/core/src/opendirector/integrations/seed_audio.py @@ -11,10 +11,11 @@ def is_seed_audio(model_id): return isinstance(model_id, str) and model_id.startswith(MODEL_PREFIX) -def request_body(config, prompt, parameters, images=(), audios=(), audio_role='reference_audio'): +def request_body(config, prompt, parameters, images=(), audios=(), audio_role='reference_audio', videos=()): content = [{'type': 'text', 'text': prompt}] content.extend({'type': 'image_url', 'role': 'reference_image', 'image_url': {'url': image}} for image in images) content.extend({'type': 'audio_url', 'role': audio_role, 'audio_url': {'url': audio}} for audio in audios) + content.extend({'type': 'video_url', 'role': 'reference_video', 'video_url': {'url': video}} for video in videos) body = {'model': config['modelId'], 'content': content, 'output_format': parameters.get('output_format') or 'mp3'} audio = {key: parameters[key] for key in @@ -40,6 +41,11 @@ def dubbing_body(config, video_url, parameters, subtitle_url=None): return body +def video_type(data): + brand = data[8:12] if data[4:8] == b'ftyp' else b'' + return 'video/quicktime' if brand in {b'qt ', b'qt'} else 'video/mp4' + + def artifact_suffix(url, allowed, default): suffix = urlsplit(url).path.rsplit('.', 1)[-1].lower() return suffix if suffix in allowed else default diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index 24fb64959..314eecd6b 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -20,7 +20,7 @@ from opendirector.integrations.generation_errors import checked, protocol_failure, provider_failure, transport_failure from opendirector.integrations.seed_audio import (audio_artifacts as seed_audio_artifacts, is_seed_audio, dubbing_artifacts as seed_audio_dubbing_artifacts, dubbing_body as seed_audio_dubbing_body, - request_body as seed_audio_body) + request_body as seed_audio_body, video_type as seed_audio_video_type) from opendirector.integrations import tos_transfer from opendirector.media.probe import require_ffprobe @@ -239,7 +239,7 @@ async def query(): await asyncio.sleep(self.poll_interval) if kind == "audio" and is_seed_audio(config["modelId"]) and task["parameters"].get("taskType") == "dubbing": if not prepared["videos"]: - raise ProjectError("翻配需要引用一段视频。", 422, code="audio_reference_video") + raise ProjectError("翻配需要引用一段视频。", 422, code="audio_dubbing_source") source = await self._publish_media(config, task["id"], prepared["videos"][0], "mp4", "video/mp4", noun="视频") subtitle_url = None @@ -260,9 +260,16 @@ async def query(): await extra_ready(role, variant, track, extra_suffix, url) return artifacts[0][2], await self._download(client, artifacts[0][1], secrets=secrets) if kind == "audio" and is_seed_audio(config["modelId"]): + videos = [] + for data in prepared['videos']: + content_type = seed_audio_video_type(data) + videos.append(await self._publish_media( + config, task["id"], data, "mov" if content_type == "video/quicktime" else "mp4", + content_type, noun="视频")) payload = seed_audio_body(config, prompt, task["parameters"], prepared['images'], prepared['audios'], - audio_role=prepared.get('audio_role', 'reference_audio')) + audio_role=prepared.get('audio_role', 'reference_audio'), + videos=videos) request_size(payload, prepared['rules']['requestBytes']) async with client.stream("POST", endpoint(config["url"], "/contents/generations"), headers=headers, json=payload) as response: diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index 43ff2231d..b1b6427b7 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -4784,6 +4784,9 @@ "audio_reference_count", "audio_reference_mix", "audio_reference_video", + "audio_dubbing_video", + "audio_dubbing_source", + "audio_separation_video", "audio_subtitle_scope", "audio_subtitle_asset", "seed_audio_storage", @@ -25184,6 +25187,9 @@ "audio_reference_count", "audio_reference_mix", "audio_reference_video", + "audio_dubbing_video", + "audio_dubbing_source", + "audio_separation_video", "audio_subtitle_scope", "audio_subtitle_asset", "seed_audio_storage", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 05ecbc556..8e9c9ceb8 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -513,7 +513,7 @@ export interface ContractInput { } export interface ContractIssueInput extends ContractInput { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_dubbing_video" | "audio_dubbing_source" | "audio_separation_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId?: string | null; readonly field?: string | null; @@ -2586,7 +2586,7 @@ export interface Contract { } export interface ContractIssue extends Contract { - readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; + readonly code: "timeline_package_invalid" | "timeline_package_too_large" | "timeline_revision_missing" | "timeline_import_missing" | "timeline_import_conflict" | "timeline_registration_rejected" | "timeline_font_too_large" | "timeline_font_unavailable" | "timeline_font_unsupported" | "timeline_font_invalid" | "timeline_font_fingerprint" | "timeline_font_coverage" | "timeline_font_total_bytes" | "timeline_font_unverified" | "timeline_font_mime" | "timeline_bundled_font_fingerprint" | "timeline_bundled_font_unavailable" | "invalid_input" | "revision_conflict" | "version_required" | "role_restricted" | "canvas_run_layout_group" | "canvas_run_layout_conflict" | "canvas_run_layout_extent" | "canvas_run_layout_shared_object" | "missing_object" | "reference_invalid" | "result_not_adoptable" | "image_quality_unsupported" | "keyframe_unsupported" | "keyframe_mode" | "keyframe_kind" | "keyframe_count" | "keyframe_needs_reference" | "keyframe_time" | "keyframe_image" | "bigmodel_video_model" | "bigmodel_video_output" | "bigmodel_video_image" | "bigmodel_video_frames" | "bigmodel_video_prompt" | "bigmodel_video_cancel" | "kling_model" | "kling_mode" | "kling_image" | "kling_frames" | "kling_prompt" | "kling_aspect" | "kling_output" | "kling_cancel" | "higgsfield_model" | "higgsfield_key" | "higgsfield_output" | "higgsfield_parameters" | "higgsfield_mode" | "higgsfield_image" | "higgsfield_format" | "higgsfield_media_size" | "higgsfield_duration" | "higgsfield_reference_count" | "higgsfield_reference_changed" | "higgsfield_frames" | "higgsfield_references" | "higgsfield_prompt" | "capability_unavailable" | "capability_paused" | "capability_connection_changed" | "capability_unsupported" | "preview_expired" | "storage_unavailable" | "submission_unknown" | "provider_error" | "audio_music_unsupported" | "audio_mode_required" | "audio_task_unsupported" | "seed_audio_base_url" | "audio_reference_image" | "audio_reference_audio" | "audio_reference_count" | "audio_reference_mix" | "audio_reference_video" | "audio_dubbing_video" | "audio_dubbing_source" | "audio_separation_video" | "audio_subtitle_scope" | "audio_subtitle_asset" | "seed_audio_storage" | "seed_audio_storage_rejected" | "seed_audio_storage_timeout" | "seed_audio_storage_unreachable" | "moss_speech_text" | "moss_speech_voice" | "moss_speech_reference" | "moss_prompt_limit" | "moss_image_size" | "moss_image_reference" | "moss_layout_reference" | "bigmodel_image_size" | "bigmodel_image_reference" | "bigmodel_image_prompt" | "minimax_image_reference" | "minimax_image_count" | "minimax_image_bytes" | "minimax_speech_text" | "minimax_speech_voice" | "minimax_speech_reference" | "minimax_speech_model" | "zhipu_speech_text" | "zhipu_speech_voice" | "zhipu_speech_reference" | "voice_library_unsupported" | "voice_connection_changed" | "voice_reference_required" | "voice_transcript_required" | "voice_transcript_too_long" | "voice_description_too_long" | "voice_not_found" | "voice_delete_unsupported" | "voice_consent_required" | "voice_name_invalid" | "voice_audio_invalid" | "voice_format" | "voice_size" | "voice_duration" | "voice_provider_protocol" | "voice_provider_error" | "voice_provider_timeout" | "voice_model_unsupported" | "voice_name_taken" | "voice_provider_quota" | "model_storage_invalid" | "model_storage_incomplete"; readonly message: string; readonly objectId: string | null; readonly field: string | null; diff --git a/tests/test_localization.py b/tests/test_localization.py index 97def31eb..cf0ffd624 100644 --- a/tests/test_localization.py +++ b/tests/test_localization.py @@ -40,6 +40,21 @@ def test_a_side_artifact_is_refused_in_the_interface_language(): assert localized_error(request('zh-CN'), chinese=chinese, status=422, code=code) == chinese +def test_a_video_reference_is_refused_in_the_interface_language(): + for code, chinese, english in [ + ('audio_reference_video', '参考视频需为 MP4 或 MOV,时长 4 秒至 6 分钟。', + 'A video reference must be MP4 or MOV, 4 seconds to 6 minutes.'), + ('audio_dubbing_video', '翻配视频需为 MP4,时长 4 秒至 6 分钟。', + 'A dubbing source must be an MP4 clip of 4 seconds to 6 minutes.'), + ('audio_dubbing_source', '翻配需要引用一段视频。', + 'Dubbing needs a source video to re-voice.'), + ('audio_separation_video', '分轨只接收一段音频,不支持视频。', + 'Track separation takes one audio input and no video.'), + ]: + assert localized_error(request('en-US'), chinese=chinese, status=422, code=code) == english + assert localized_error(request('zh-CN'), chinese=chinese, status=422, code=code) == chinese + + def test_accept_language_uses_the_primary_language() -> None: assert wants_english(request("zh-CN,zh;q=0.9")) is False assert wants_english(request("zh-Hant")) is False diff --git a/tests/test_seed_audio.py b/tests/test_seed_audio.py index bd6dd7bb6..acdf91342 100644 --- a/tests/test_seed_audio.py +++ b/tests/test_seed_audio.py @@ -16,7 +16,7 @@ from opendirector.domain.input_rules import input_rules from opendirector.domain.projects import ProjectError from opendirector.integrations.seed_audio import (audio_artifacts, dubbing_artifacts, dubbing_body, - request_body) + request_body, video_type) from opendirector.integrations.volcengine import VolcengineGeneration from test_creation_contracts import entity, model as public_model from test_creation_canvas_service import project # noqa: F401 (pytest fixture) @@ -232,15 +232,55 @@ def test_voice_references_must_be_two_to_thirty_seconds(tmp_path): assert failure.value.code == 'audio_reference_audio' -def test_video_references_stay_unsupported(tmp_path): +def test_a_video_reference_travels_as_a_reference_video(tmp_path, monkeypatch): store, owner, _, _, _ = reference_store(tmp_path) video = {'id': str(UUID(int=40)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', 'fingerprint': 'fixture', 'durationMs': 5000} original = store.asset store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + ready = prepared(store, owner, [video]) + assert len(ready['videos']) == 1 and ready['audios'] == [] and ready['images'] == [] + assert [entry['role'] for entry in ready['manifest']] == ['reference_video'] + body = request_body(config(), ready['prompt'], {'output_format': 'mp3'}, ready['images'], + ready['audios'], videos=['https://storage.example/od/clip.mp4']) + assert body['content'][-1] == {'type': 'video_url', 'role': 'reference_video', + 'video_url': {'url': 'https://storage.example/od/clip.mp4'}} + + +def test_a_video_and_a_voice_reference_travel_together(tmp_path): + store, owner, _, voice, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=41)), 'name': '片段.mov', 'type': 'video/quicktime', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': 8000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + ready = prepared(store, owner, [video, voice]) + assert len(ready['videos']) == 1 and len(ready['audios']) == 1 + assert [entry['role'] for entry in ready['manifest']] == ['reference_video', 'reference_audio'] + + +def test_a_video_reference_cannot_be_mixed_with_an_image(tmp_path): + store, owner, image, _, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=42)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': 5000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + with pytest.raises(ProjectError) as failure: + prepared(store, owner, [image, video]) + assert failure.value.code == 'audio_reference_mix' + + +def test_separation_takes_no_video(tmp_path): + store, owner, _, _, _ = reference_store(tmp_path) + video = {'id': str(UUID(int=43)), 'name': '片段.mp4', 'type': 'video/mp4', 'kind': 'video', + 'fingerprint': 'fixture', 'durationMs': 5000} + original = store.asset + store.asset = lambda project_id, asset_id: (b'private', video) if asset_id == video['id'] else original(project_id, asset_id) + task = store_task(owner, [video]) + task['parameters']['taskType'] = 'separation' + from opendirector.integrations.reference_inputs import generation_references with pytest.raises(ProjectError) as failure: - prepared(store, owner, [video]) - assert failure.value.code == 'audio_reference_video' + generation_references(store, task, config()) + assert failure.value.code == 'audio_separation_video' def dubbing_task(owner, refs, **parameters): @@ -345,7 +385,7 @@ def test_dubbing_rejects_a_video_outside_the_accepted_duration(tmp_path): store, owner, video = dubbing_store(tmp_path, 3000) with pytest.raises(ProjectError) as failure: dubbing_ready(store, owner, [video]) - assert failure.value.code == 'audio_reference_video' + assert failure.value.code == 'audio_dubbing_video' def test_dubbing_cannot_mix_a_video_with_voice_samples(tmp_path): @@ -368,9 +408,10 @@ def test_dubbing_carries_a_custom_subtitle_url(tmp_path): assert ready['subtitle'] is None -def test_a_subtitle_asset_travels_with_the_dubbed_video(tmp_path): +@pytest.mark.parametrize('mime', ['text/plain', 'application/x-subrip']) +def test_a_subtitle_asset_travels_with_the_dubbed_video(tmp_path, mime): store, owner, video = dubbing_store(tmp_path, 6000) - srt = {'id': str(UUID(int=60)), 'name': '台词.srt', 'type': 'text/plain', 'kind': 'text', + srt = {'id': str(UUID(int=60)), 'name': '台词.srt', 'type': mime, 'kind': 'text', 'fingerprint': 'fixture'} original = store.asset body = b'1\n00:00:00,000 --> 00:00:02,000\n\n' @@ -463,6 +504,52 @@ def handler(request): 'audio_url': {'url': 'data:audio/wav;base64,AAAA'}} +def test_the_declared_video_type_follows_the_container_brand(): + assert video_type(b'\x00\x00\x00\x18ftypmp42') == 'video/mp4' + assert video_type(b'\x00\x00\x00\x14ftypqt ') == 'video/quicktime' + + +@pytest.mark.anyio +async def test_a_video_reference_is_published_before_the_request(monkeypatch): + from opendirector.integrations import volcengine as module + audio = subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', + 'sine=frequency=440:sample_rate=44100', '-t', '0.2', + '-threads', '1', '-f', 'mp3', 'pipe:1'], + capture_output=True, check=True).stdout + posted = [] + + def handler(request): + if request.method == 'GET': + return httpx.Response(200, content=audio, headers={'content-type': 'audio/mpeg'}) + posted.append(json.loads(request.content)) + return httpx.Response(200, json={'id': '0219', 'model': MODEL, + 'content': {'audios': [{'url': 'http://fixture.invalid/api/v3/mix.mp3'}]}}) + + clip = b'\x00\x00\x00\x18ftypmp42' + ready = {'prompt': '跟着画面配一段动效声。', 'images': [], 'audios': ['data:audio/wav;base64,AAAA'], + 'videos': [clip], 'manifest': [], 'subtitle': None, 'continueFrom': None, + 'continueSize': None, 'control': None, 'guides': [], 'audio_role': 'reference_audio', + 'rules': input_rules({**config(), 'kind': 'audio'})} + monkeypatch.setattr(module, 'generation_references', lambda store, task, configuration: ready) + published = [] + + async def publish(configuration, task_id, data, suffix, content_type, *, noun='素材'): + published.append((data, suffix, content_type, noun)) + return 'https://storage.example/od/clip.mp4' + + monkeypatch.setattr(VolcengineGeneration, '_publish_media', staticmethod(publish)) + provider = VolcengineGeneration(None, transport=httpx.MockTransport(handler), poll_interval=0) + task = {'id': 'job', 'kind': 'audio', 'projectId': 'p', 'prompt': '跟着画面配一段动效声。', + 'referenceIds': ['asset'], 'parameters': {'taskType': 'reference', 'output_format': 'mp3'}} + suffix, _ = await provider.generate({**config(), 'apiKey': 'fixture-key'}, task, lambda external_id: None) + assert suffix == 'mp3' + assert published == [(clip, 'mp4', 'video/mp4', '视频')] + assert posted[0]['content'][-1] == {'type': 'video_url', 'role': 'reference_video', + 'video_url': {'url': 'https://storage.example/od/clip.mp4'}} + assert posted[0]['content'][1] == {'type': 'audio_url', 'role': 'reference_audio', + 'audio_url': {'url': 'data:audio/wav;base64,AAAA'}} + + def test_separation_refuses_more_than_six_minutes_in_one_clip(tmp_path): store, owner, _, _, _ = reference_store(tmp_path) too_long = {'id': str(UUID(int=71)), 'name': '长访谈.wav', 'type': 'audio/wav', 'kind': 'audio', From 8a90ba8c0c554b7ff5328fdd3f5ecbb292caac44 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:56:16 +0800 Subject: [PATCH 37/58] [bugfix] canvas: let a video feed a dubbing node MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary A video node could not feed a dubbing node. The canvas type matrix let an audio node take a video only from an image, so `reference.add` answered `reference_invalid` for exactly the reference dubbing needs and the assistant could not start the job at all. Both tables change together because the assembly test asserts the Python set and the TypeScript table are the same product truth. ## verification - `Ran:` tests/test_creation_assembly.py, tests/test_agent_seed_audio.py - Before the change the assistant test failed in `reference.add` with `reference_invalid` "该节点类型不能作为目标节点的参考。" --- packages/core/src/opendirector/application/creation_canvas.py | 2 +- src/canvas/connectionPolicy.ts | 2 +- tests/canvasReferenceMigration.test.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 339149a28..24b95d783 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -32,7 +32,7 @@ 'reference': 'references', 'editor_document': 'editorDocuments', 'asset': 'assets', 'job': 'jobs', 'result': 'results'} DOWNSTREAM = {'text': {'text', 'image', 'video', 'motion'}, 'image': {'text', 'image', 'video', 'audio', 'timeline', 'subject', 'motion'}, - 'video': {'text', 'video', 'timeline', 'subject', 'motion'}, 'audio': {'text', 'video', 'audio', 'timeline', 'motion'}, + 'video': {'text', 'video', 'audio', 'timeline', 'subject', 'motion'}, 'audio': {'text', 'video', 'audio', 'timeline', 'motion'}, 'subject': {'image', 'video', 'audio'}} diff --git a/src/canvas/connectionPolicy.ts b/src/canvas/connectionPolicy.ts index 3508ffd4a..f99a9422b 100644 --- a/src/canvas/connectionPolicy.ts +++ b/src/canvas/connectionPolicy.ts @@ -25,7 +25,7 @@ export const downstreamKinds: Partial< > = { text: ["text", "image", "video", "motion"], image: ["text", "image", "video", "audio", "timeline", "subject", "motion"], - video: ["text", "video", "timeline", "subject", "motion"], + video: ["text", "video", "audio", "timeline", "subject", "motion"], audio: ["text", "video", "audio", "timeline", "motion"], subject: ["image", "video", "audio"], }; diff --git a/tests/canvasReferenceMigration.test.ts b/tests/canvasReferenceMigration.test.ts index c7f6488b0..b5beb4d39 100644 --- a/tests/canvasReferenceMigration.test.ts +++ b/tests/canvasReferenceMigration.test.ts @@ -40,7 +40,7 @@ const kinds = [ const allowed: Record<(typeof kinds)[number], readonly CanvasNodeKind[]> = { text: ["text", "image", "video"], image: ["text", "image", "video", "audio", "subject", "timeline"], - video: ["text", "video", "subject", "timeline"], + video: ["text", "video", "audio", "subject", "timeline"], audio: ["text", "video", "audio", "timeline"], subject: ["image", "video", "audio"], timeline: [], From 9d9a561f5f3df79c3b8aa5c8f0ff45274a1e7f86 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:56:46 +0800 Subject: [PATCH 38/58] [bugfix] canvas: send an audio node the media its model declares MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary Every media reference attached to an audio generation was demoted to `context_only`, so no image, video or voice clip could ever reach the provider. The audio branch was written when an audio node meant speech or music, and only a music recording was allowed through; Seed Audio dubbing, separation and reference tasks all take media, and their declared capability contract already says so. Transmission now follows the same capability contract the rest of the product uses: a media kind the model accepts, with a remaining slot for that kind, travels as `content`; anything else stays `context_only`. ## verification - `Ran:` tests/test_seed_audio.py, tests/test_agent_seed_audio.py, tests/test_creation_parameters.py - Without the change the assistant test failed before any request with "翻配需要引用一段视频。" because the accepted video never left the project. --- .../core/src/opendirector/application/creation_canvas.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index 24b95d783..a541239af 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -144,9 +144,10 @@ def reference_policy(spec, values, rules=None, *, selected_frame=False): frame_roles = set(rules.frameRoles) if rules and rules.frameRoles else {'first_frame'} for value in values: kind = value.asset.kind - # Speech reads its own text; only a music model that follows a recording takes one. - ignored = spec.kind == 'audio' and not (kind == 'audio' and spec.parameters.creationType == 'music' - and rules is not None and 'audio' in rules.allowedKinds) + accepted = rules is not None and kind in rules.allowedKinds and not ( + (kind == 'image' and not rules.maxImages) or (kind == 'video' and not rules.maxVideos) + or (kind == 'audio' and not rules.maxAudios)) + ignored = spec.kind == 'audio' and not (kind in {'image', 'video', 'audio'} and accepted) if spec.kind == 'video' and spec.parameters.videoMode == 'first_frame': ignored = kind not in {'text', 'image'} or kind == 'image' and (value.subjectRole is not None or not selected_frame or value.role not in frame_roles) if selected_frame and value.role in {'first_frame', 'last_frame'} and ignored: From d9bffc682ceb27bccda4b0f05c65a05ff66e5ac9 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:57:27 +0800 Subject: [PATCH 39/58] [bugfix] audio: run the operation Seed Audio declares and record what it returns ## summary The Seed Audio route never ran the operation the task asked for. The parameter builder wrote the operation under `task`, while the adapter and the reference builder read `taskType`, so dubbing and separation fell back to plain text-to-audio: a dubbing job carried no video and the provider answered with an ordinary speech file the project accepted as a success. Dubbing also returns a re-voiced video rather than audio, which the job contract refused: an audio execution could only own an audio asset. The execution record now names the media the provider delivers, and the result is registered with that kind instead of the model kind. ## verification - `Ran:` tests/test_agent_seed_audio.py, tests/test_seed_audio.py, tests/test_creation_parameters.py, tests/test_creation_generation_service.py, tests/test_creation_contracts.py - Without the parameter change the assistant test posted a text-only body and failed on the missing `video_url`. - Without the delivered-kind record the same test failed at save with "Job execution/output kind differs from its inputs". --- .../application/creation_generation.py | 14 ++++---- .../domain/creation/generation.py | 5 ++- src/contracts/creation.schema.json | 34 +++++++++++++++++++ src/contracts/generated.ts | 2 ++ 4 files changed, 48 insertions(+), 7 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index e17b46ba5..7b3923448 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -214,7 +214,7 @@ def _parameters(self, spec, config, node, records): if intent.get('durationFromReference', True) and recording['durationMs']: params['duration'] = reference_music_seconds(recording['durationMs'] / 1000) elif spec.kind == 'audio' and input_rules(config)['profile'] == 'seed-audio': - params = {'task': intent.get('taskType', 'text2audio'), + params = {'taskType': intent.get('taskType', 'text2audio'), 'output_format': intent.get('outputFormat', 'mp3')} for key, name in (('speech_rate', 'speechRate'), ('loudness_rate', 'loudnessRate'), ('pitch_rate', 'pitchRate')): @@ -312,7 +312,8 @@ def _execution(kind, parameters, config): return dict(kind=kind, creationType='music', format='mp3', maxDurationSeconds=parameters['duration'], scoreMode=parameters.get('score_mode'), seed=parameters.get('seed')) if kind == 'audio' and input_rules(config)['profile'] == 'seed-audio': - return dict(kind=kind, taskType=parameters.get('task', 'text2audio'), + return dict(kind=kind, taskType=parameters['taskType'], + outputKind='video' if parameters['taskType'] == 'dubbing' else None, format=parameters.get('output_format', 'mp3'), sampleRate=parameters.get('sample_rate'), speechRate=parameters.get('speech_rate'), loudnessRate=parameters.get('loudness_rate'), pitchRate=parameters.get('pitch_rate'), @@ -599,9 +600,10 @@ def _commit_output(self, task, pinned, suffix, data): job = self.get_job(task['projectId'], task['id']) handle = uuid5(job.id, 'output-upload') name = re.sub(r'[<>:"/\\|?*\x00-\x1f]', '_', task['title']).strip(' .')[:180] or job.execution.kind + primary_kind = getattr(job.execution, 'outputKind', None) or artifact_kind(suffix) or job.execution.kind if not existing: self.assets.stage_output(job.projectId, handle, with_extension(name, suffix), - cache.directory / 'output', expected_kind=job.execution.kind) + cache.directory / 'output', expected_kind=primary_kind) staged = [(uuid5(job.id, f"output-upload:{record['role']}:{record.get('variant') or ''}:{record.get('track') or ''}"), with_extension(self._artifact_name(name, record), record['suffix']), artifact_kind(record['suffix']), record) @@ -615,7 +617,7 @@ def _commit_output(self, task, pinned, suffix, data): # the provider request or reusing an obsolete adoption decision. for attempt in range(16): try: - return self._register_output(task, pinned, suffix, handle, name, staged) + return self._register_output(task, pinned, suffix, handle, name, staged, primary_kind) except ProjectError as error: if error.code != 'revision_conflict' or attempt == 15: raise @@ -626,7 +628,7 @@ def _artifact_name(name, record): if part and part != 'primary'] return f"{name}-{'-'.join(parts)}" if parts else name - def _register_output(self, task, pinned, suffix, handle, name, staged=()): + def _register_output(self, task, pinned, suffix, handle, name, staged=(), kind=None): before = self.projects.snapshot(task['projectId']) job = next(j for j in before.jobs if str(j.id) == task['id']) if job.status == 'succeeded': @@ -639,7 +641,7 @@ def _register_output(self, task, pinned, suffix, handle, name, staged=()): origin = next((i for i in before.canvasItems if i.id == job.originItemId), None) command = parse_command(dict(commandId=uuid5(job.id, f'register-result:{job.revision}:{spec.revision}:{origin.revision if origin else 0}'), projectId=job.projectId, type='asset.import', expectedVersions=[version('job', job), version('generation_spec', spec), *([version('canvas_item', origin)] if origin else [])], - payload=dict(uploadHandle=handle, name=with_extension(name, suffix), expectedKind=job.execution.kind))) + payload=dict(uploadHandle=handle, name=with_extension(name, suffix), expectedKind=kind or job.execution.kind))) extras = [(gateway().upload_asset_id(job.projectId, extra_handle), record) for extra_handle, _, _, record in staged] def apply(current, asset): current_job = next(j for j in current.jobs if j.id == job.id) diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 17c3b7fe9..8ae4abc46 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -335,6 +335,8 @@ class AudioExecution(Contract): subtitleAssetId: UUID | None = Field(default=None, exclude_if=lambda value: value is None, description='Dubbing: subtitle asset that fixed the spoken lines when the job was accepted.') creationType: Literal['audio', 'music'] = Field(default='audio', exclude_if=lambda value: value == 'audio', description='Speech or music creation mode.') + outputKind: Literal['audio', 'video'] | None = Field(default=None, exclude_if=lambda value: value is None, + description='Media the provider delivers when it differs from the model kind, as a re-voiced video does.') # Legacy, see AudioParameters.instrumental. instrumental: bool = Field(default=False, exclude_if=lambda value: value is False, description='Legacy explicit instrumental choice retained for stored records.') # A music model may end the piece earlier than this cap. @@ -390,7 +392,8 @@ def execution_identity(self): raise ValueError('Job and generation snapshot belong to different projects') if self.inputFingerprint != self.inputSnapshot.fingerprint(): raise ValueError('Job input fingerprint differs from its snapshot') - if self.execution.kind != self.inputSnapshot.spec.kind or self.asset and self.asset.kind != self.execution.kind: + output = getattr(self.execution, 'outputKind', None) or self.execution.kind + if self.execution.kind != self.inputSnapshot.spec.kind or self.asset and self.asset.kind != output: raise ValueError('Job execution/output kind differs from its inputs') if self.status == 'succeeded' and self.asset is None: raise ValueError('Successful jobs require an actual output asset') diff --git a/src/contracts/creation.schema.json b/src/contracts/creation.schema.json index b1b6427b7..50c90de66 100644 --- a/src/contracts/creation.schema.json +++ b/src/contracts/creation.schema.json @@ -1377,6 +1377,23 @@ "title": "Creationtype", "type": "string" }, + "outputKind": { + "anyOf": [ + { + "enum": [ + "audio", + "video" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Media the provider delivers when it differs from the model kind, as a re-voiced video does.", + "title": "Outputkind" + }, "instrumental": { "default": false, "description": "Legacy explicit instrumental choice retained for stored records.", @@ -21694,6 +21711,23 @@ "title": "Creationtype", "type": "string" }, + "outputKind": { + "anyOf": [ + { + "enum": [ + "audio", + "video" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Media the provider delivers when it differs from the model kind, as a re-voiced video does.", + "title": "Outputkind" + }, "instrumental": { "default": false, "description": "Legacy explicit instrumental choice retained for stored records.", diff --git a/src/contracts/generated.ts b/src/contracts/generated.ts index 8e9c9ceb8..775a7ebcb 100644 --- a/src/contracts/generated.ts +++ b/src/contracts/generated.ts @@ -139,6 +139,7 @@ export interface AudioExecutionInput extends ContractInput { readonly sourceLanguage?: string | null; readonly subtitleAssetId?: string | null; readonly creationType?: "audio" | "music"; + readonly outputKind?: "audio" | "video" | null; readonly instrumental?: boolean; readonly maxDurationSeconds?: number | null; readonly scoreMode?: "melody" | "full" | null; @@ -2212,6 +2213,7 @@ export interface AudioExecution extends Contract { readonly sourceLanguage?: string | null; readonly subtitleAssetId?: string | null; readonly creationType?: "audio" | "music"; + readonly outputKind?: "audio" | "video" | null; readonly instrumental?: boolean; readonly maxDurationSeconds?: number | null; readonly scoreMode?: "melody" | "full" | null; From 9c86ac5c44814978a92ecd18fedd3c8e58fd76b7 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:57:33 +0800 Subject: [PATCH 40/58] [bugfix] models: build the public model shape in one place ## summary Four call sites rebuilt `ModelConfigPublic` by copying the resolved service record and dropping only `apiKey`. Once a model service also carried its object-storage credentials, the strict public shape rejected the extra key and every spec projection failed with `invalid_input: "storage: Extra inputs are not permitted"`, which reached the user as a refusal to submit work at all. One factory drops everything the public shape must never carry, so a future service-level field cannot break submission again. ## verification - `Ran:` tests/test_agent_seed_audio.py, tests/test_creation_parameters.py, tests/test_creation_canvas_service.py, tests/test_creation_node_versions.py - Before the change the assistant test failed with `invalid_input: "storage: Extra inputs are not permitted"` before any request was sent. --- .../core/src/opendirector/application/creation_canvas.py | 2 +- .../core/src/opendirector/application/creation_generation.py | 4 ++-- .../src/opendirector/application/creation_node_versions.py | 2 +- packages/core/src/opendirector/domain/creation/models.py | 5 +++++ 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index a541239af..13c301eef 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -985,7 +985,7 @@ def projection(self, project_id, snapshot=None): key = (str(spec.modelConfigId), spec.kind) if key not in public_models: config = models.resolve(str(spec.modelConfigId), 'agent' if spec.kind == 'text' else spec.kind) - public_models[key] = ModelConfigPublic.model_validate({k: v for k, v in config.items() if k != 'apiKey'} | {'inputRules': input_rules(config)}) + public_models[key] = ModelConfigPublic.from_service(config, input_rules(config)) model = public_models[key] spec, references = current_generation_inputs(snapshot, spec, model.inputRules, visible) for reference in references: diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 7b3923448..2053de074 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -402,7 +402,7 @@ def prepare(self, command, *, session=None, source='ui', agent_origin=None): if voice_spec is not None and voice_spec.kind == 'audio' and voice_spec.parameters.creationType == 'audio': try: voice_config = self.configs.resolve(str(voice_spec.modelConfigId), 'audio') - public = ModelConfigPublic.model_validate({key: value for key, value in voice_config.items() if key != 'apiKey'} | {'inputRules': input_rules(voice_config)}) + public = ModelConfigPublic.from_service(voice_config, input_rules(voice_config)) prepared_spec, references = current_generation_inputs(initial, voice_spec, public.inputRules) validate_generation(prepared_spec, public, references) self.voices.validate_selection(voice_config, prepared_spec.parameters.voice, prepared_spec.parameters.voiceSelection) @@ -440,7 +440,7 @@ def accept(before): intermediate = ProjectSnapshot.model_validate(data) spec = next(s for s in intermediate.generationSpecs if s.id == old.id) config = self.configs.resolve(str(spec.modelConfigId), 'agent' if spec.kind == 'text' else spec.kind) - public = ModelConfigPublic.model_validate({key: value for key, value in config.items() if key != 'apiKey'} | {'inputRules': self.availability.effective_input_rules(config)}) + public = ModelConfigPublic.from_service(config, self.availability.effective_input_rules(config)) spec, resolved = current_generation_inputs(intermediate, spec, public.inputRules) spec = execution_spec(spec, resolved, public.inputRules) try: diff --git a/packages/core/src/opendirector/application/creation_node_versions.py b/packages/core/src/opendirector/application/creation_node_versions.py index 089ea7514..30ba3cb68 100644 --- a/packages/core/src/opendirector/application/creation_node_versions.py +++ b/packages/core/src/opendirector/application/creation_node_versions.py @@ -37,7 +37,7 @@ def available_model(projects, frozen): """A removed or repurposed model remains evidence, never an implicit fallback.""" try: config = gateway().models(projects.local.repository).resolve(str(frozen.modelConfigId), frozen.kind) - public = ModelConfigPublic.model_validate({k: v for k, v in config.items() if k != 'apiKey'} | {'inputRules': input_rules(config)}) + public = ModelConfigPublic.from_service(config, input_rules(config)) fields = ('kind', 'url', 'modelId', 'protocol', 'connectionType', 'videoAdapter') if any(getattr(public, field) != getattr(frozen, field) for field in fields): return None diff --git a/packages/core/src/opendirector/domain/creation/models.py b/packages/core/src/opendirector/domain/creation/models.py index cd2366fed..4d7acfd24 100644 --- a/packages/core/src/opendirector/domain/creation/models.py +++ b/packages/core/src/opendirector/domain/creation/models.py @@ -251,6 +251,11 @@ class ModelConfigPublic(ModelConnection): availability: ModelAvailability | None = Field(default=None, exclude_if=lambda value: value is None, description='Ephemeral observation, never persisted in project snapshots.') + @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}) + class ModelConfigWrite(ModelConnection): """Only the model-settings write boundary accepts a credential.""" From 68c94347971ca4c8775aac35ffe700e4b8f0cb59 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 15:57:39 +0800 Subject: [PATCH 41/58] [test] agent: dub a video through the assistant ## summary Every Seed Audio test built its own task dictionary, so the assistant and canvas path was never exercised: parameter projection, reference transmission, the outbound body and result registration could each break while the suite stayed green. These tests drive `execute_command` the way the agent does and check the request that left the process, the files that came back, and the timeline that can hold the extra voice track. Writing them exposed four real defects: the video node could not reference the audio node, the reference was demoted to `context_only`, the operation key was never read, and an audio execution could not own the video that dubbing returns. ## verification - `Ran:` tests/test_agent_seed_audio.py - The request assertion requires a `dubbing_video` reference and no text. - The timeline assertion requires the generated composite track to be placeable as an audio clip beside the dubbed video. --- tests/test_agent_seed_audio.py | 170 +++++++++++++++++++++++++++++++++ 1 file changed, 170 insertions(+) create mode 100644 tests/test_agent_seed_audio.py diff --git a/tests/test_agent_seed_audio.py b/tests/test_agent_seed_audio.py new file mode 100644 index 000000000..8a114b22c --- /dev/null +++ b/tests/test_agent_seed_audio.py @@ -0,0 +1,170 @@ +"""Dubbing submitted the way the assistant submits it: one command, real artifacts. + +The canvas and the assistant share the same service, so this test drives the +agent tool gateway instead of calling the command directly and checks the +resulting project, request body and files. +""" +import json +import shutil +import subprocess +from uuid import UUID, uuid4 + +import httpx +import pytest + +from opendirector.agent.tools import AgentTools +from opendirector.application.creation_canvas import asset_ref +from opendirector.application.creation_tool_assets import CreationToolAssets +from opendirector.integrations import volcengine as module +from opendirector.infrastructure.model_configs import ModelConfigs +from test_creation_canvas_service import project, send, ver # noqa: F401 (pytest fixtures) +from test_creation_generation_service import anyio_backend # noqa: F401 (pytest fixture) +from test_creation_parameters import done, setup +from test_seed_audio import CONTENT_BASE, MODEL + + +pytestmark = pytest.mark.cpu + + +def ffmpeg(*arguments): + return subprocess.run(['ffmpeg', '-v', 'error', *arguments, '-threads', '1', 'pipe:1'], + capture_output=True, check=True).stdout + + +def clip(seconds=5): + return ffmpeg('-f', 'lavfi', '-i', f'color=c=teal:s=160x120:d={seconds}:r=12', + '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-movflags', 'frag_keyframe+empty_moov', + '-f', 'mp4') + + +def wav(seconds=0.3, frequency=440): + return ffmpeg('-f', 'lavfi', '-i', f'sine=frequency={frequency}:sample_rate=44100', + '-t', str(seconds), '-f', 'mp3') + + +def storage_account(runner, spec, monkeypatch): + runner.configs.save_storage(str(spec.modelConfigId), {'accessKey': 'ak', 'secretKey': 'sk', + 'bucket': 'bucket-a', 'region': 'cn-beijing'}) + monkeypatch.setattr(module.tos_transfer, 'put', lambda *arguments, **keywords: None) + monkeypatch.setattr(module.tos_transfer, 'presign', + lambda bucket, region, key, access_key, secret_key, expires=0: + f'https://tos.example/{key}') + + +async def dubbed(project, tmp_path, monkeypatch): + store, pid, session = project + assets = CreationToolAssets(store) + record = assets.import_file(str(pid), str(UUID(int=70)), 'clase.mp4', clip(), session) + video = assets.assets.get(pid, record['id']) + dubbed, track, subtitle = clip(5), wav(), b'1\n00:00:00,000 --> 00:00:01,000\nHello\n' + posted = [] + + def handler(request): + if request.method == 'GET': + suffix = request.url.path.rsplit('.', 1)[-1] + body, kind = {'mp4': (dubbed, 'video/mp4'), 'mp3': (track, 'audio/mpeg'), + 'srt': (subtitle, 'application/x-subrip')}[suffix] + return httpx.Response(200, content=body, headers={'content-type': kind}) + posted.append(json.loads(request.content)) + return httpx.Response(200, json={'content': { + 'video_url': 'http://fixture.invalid/api/v3/dubbed.mp4', + 'audios': [{'url': 'http://fixture.invalid/api/v3/mix.mp3', 'type': 'composite'}], + 'subtitles': [{'format': 'srt', 'url': 'http://fixture.invalid/api/v3/line.srt'}]}}) + + runner, item, spec_id = setup(project, 'audio', dict( + mode='unified', creationType='audio', taskType='dubbing', targetLanguage='en', + outputFormat='mp3'), handler, protocol='volcengine', model=MODEL, url=CONTENT_BASE) + snapshot = store.snapshot(pid) + spec = next(s for s in snapshot.generationSpecs if s.id == spec_id) + current = next(i for i in snapshot.canvasItems if i.id == item.id) + storage_account(runner, spec, monkeypatch) + source = uuid4() + assert send(store, pid, 'canvas.show', session=session, item=dict( + id=source, projectId=pid, kind='video', + binding=dict(role='material', objectRef=asset_ref(video)))).status == 'applied' + assert send(store, pid, 'reference.add', session=session, + versions=[ver('generation_spec', spec), ver('canvas_item', current)], + reference=dict(id=uuid4(), projectId=pid, targetSpecId=spec_id, order=1, + binding='follow_current', source=dict(id=source), + role='reference')).status == 'applied' + + business = AgentTools(store, runner, ModelConfigs(tmp_path)) + snapshot = store.snapshot(pid) + spec = next(s for s in snapshot.generationSpecs if s.id == spec_id) + current = next(i for i in snapshot.canvasItems if i.id == item.id) + turn = uuid4() + receipt = await business.execute( + pid, turn, session, 'call-1', 'execute_command', + {'type': 'generation.submit', + 'expectedVersions': [ver('generation_spec', spec), ver('canvas_item', current)], + 'payload': {'specId': str(spec_id), 'expectedSpecRevision': spec.revision, + 'originItemId': str(item.id)}}, + [], None) + assert receipt['status'] == 'accepted', receipt + await done(runner) + + (body,) = posted + assert body['content'] == [{'type': 'video_url', 'role': 'dubbing_video', + 'video_url': {'url': body['content'][0]['video_url']['url']}}] + assert body['dubbing_config'] == {'target_language': 'en'} + assert 'text' not in body + + after = store.snapshot(pid) + job = after.jobs[-1] + assert job.status == 'succeeded', job.errorDetails + return runner, store, pid, session, turn, body, after + + +def job_of(snapshot, turn): + return next(job for job in snapshot.jobs if job.agentRunId == turn) + + +@pytest.mark.anyio +async def test_the_assistant_dubs_a_video_into_the_target_language(project, tmp_path, monkeypatch): + runner, store, pid, session, turn, body, after = await dubbed(project, tmp_path, monkeypatch) + assert body['content'] == [{'type': 'video_url', 'role': 'dubbing_video', + 'video_url': {'url': body['content'][0]['video_url']['url']}}] + assert body['dubbing_config'] == {'target_language': 'en'} + assert 'text' not in body + + job = job_of(after, turn) + assert job.inputSnapshot.spec.parameters.targetLanguage == 'en' + assert job.inputSnapshot.spec.parameters.taskType == 'dubbing' + assert [(entry.role, entry.asset.kind) for entry in job.inputSnapshot.references] == [('reference', 'video')] + assert job.execution.outputKind == 'video' + assert sorted(r.role for r in after.results if r.jobId == job.id) == ['audio_track', 'primary', 'subtitle'] + adopted = next(a for a in after.assets if a.id == job.asset.assetId) + assert adopted.kind == 'video' + names = sorted(a.name for a in after.assets if a.provenance.jobId == job.id) + assert names == ['Make an output-audio_track-composite-0.mp3', 'Make an output-subtitle-target_srt.srt', + 'Make an output.mp4'], names + + +@pytest.mark.anyio +async def test_the_assistant_places_the_dubbed_voice_on_the_timeline(project, tmp_path, monkeypatch): + runner, store, pid, session, turn, _, after = await dubbed(project, tmp_path, monkeypatch) + job = job_of(after, turn) + voice = next(r for r in after.results if r.jobId == job.id and r.role == 'audio_track') + picture = next(a for a in after.assets if a.id == job.asset.assetId) + document = uuid4() + + business = AgentTools(store, runner, ModelConfigs(tmp_path)) + receipt = await business.execute( + pid, turn, session, 'call-2', 'execute_command', + {'type': 'editor.create', + 'payload': {'document': { + 'id': str(document), 'projectId': str(pid), 'kind': 'timeline', + 'data': {'width': 160, 'height': 120, 'fps': 24, 'tracks': [ + {'id': 'visual', 'title': 'Picture', 'kind': 'visual', + 'clips': [{'id': 'picture', 'inPoint': 0, 'outPoint': 5, + 'resource': {'asset': asset_ref(picture), 'title': 'Dubbed', 'durationSeconds': 5}}]}, + {'id': 'voice', 'title': 'Dubbed voice', 'kind': 'audio', + 'clips': [{'id': 'voice', 'start': 0, 'inPoint': 0, 'outPoint': 0.3, + 'resource': {'asset': asset_ref(next(a for a in after.assets if a.id == voice.asset.assetId)), + 'title': 'Dubbed voice', 'durationSeconds': 0.3}}]}]}}}}, + [], None) + + assert receipt['status'] == 'applied', receipt + timeline = next(d for d in store.snapshot(pid).editorDocuments if d.id == document) + assert [track.kind for track in timeline.data.tracks] == ['visual', 'audio'] + assert timeline.data.tracks[1].clips[0].resource.asset.assetId == voice.asset.assetId From 157feaf38f8dd05c12f6fdd07854d8bbf0784a16 Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 17:48:49 +0800 Subject: [PATCH 42/58] [build] repo: keep a node_modules link out of the tree ## summary A merge brought in a `node_modules` symlink pointing at an absolute path on the machine that created it, and `.gitignore` matched only the directory form, so the link passed the ignore rule. Untrack it and match both forms. ## verification - `Ran:` git ls-files node_modules (empty after the change) - `Not run:` nothing else; no source or test changed --- .gitignore | 2 +- node_modules | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) delete mode 120000 node_modules diff --git a/.gitignore b/.gitignore index 791b20f0a..3846e52d4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -node_modules/ +node_modules dist/ .DS_Store diff --git a/node_modules b/node_modules deleted file mode 120000 index 5b63a7658..000000000 --- a/node_modules +++ /dev/null @@ -1 +0,0 @@ -/home/ubuntu/projects/OpenDirector/node_modules \ No newline at end of file From d27fd35857f707caa29ad9d1b9f588668115ea7c Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 18:33:49 +0800 Subject: [PATCH 43/58] [feat] canvas: let a model declare the audio operation and collect what it needs An audio model publishes audioTasks, but the canvas dropped that list at the data boundary and only carried creationType and mode. Seed Audio 1.5 generates speech, dubs a video and separates stems from the same model, so a user could reach only the default operation. The settings now carry audioTask, targetLanguage, sourceLanguage and subtitleAssetId. dataBoundary keeps them, the projection writes the contract key taskType plus the three dubbing fields, and the reverse mapping restores them. chosenAudioTask prefers the user's choice and falls back to the first declared task, audioTaskParameters sends a language only for dubbing, subtitleChoices offers only application/x-subrip text assets, and backendBlocker refuses dubbing without a target language. Ran: node --test tests/audioTask.test.ts (5 passed) Ran: ./node_modules/.bin/tsc --noEmit (clean) Ran: npm test (1120 passed) Ran: npm run check:i18n (3872 keys, 0 problems) --- src/backend/creationProjection.ts | 7 ++ src/backend/rules.ts | 19 ++++ src/canvas/NodeComposer.tsx | 106 ++++++++++++++++++++ src/canvas/audioTask.ts | 119 +++++++++++++++++++++++ src/canvas/dataBoundary.ts | 21 ++++ src/canvas/model.ts | 4 + src/canvas/workspace/WorkspaceView.tsx | 8 ++ src/i18n/messages/en-US/generation.ts | 29 ++++++ src/i18n/messages/zh-CN/generation.ts | 29 ++++++ tests/audioTask.test.ts | 129 +++++++++++++++++++++++++ 10 files changed, 471 insertions(+) create mode 100644 src/canvas/audioTask.ts create mode 100644 tests/audioTask.test.ts diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index 8a63d3552..90e35bdc0 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -34,6 +34,7 @@ import { } from "../canvas/stageDocument.ts"; import { mediaBlobDataUrl } from "../canvas/localMediaRuntime.ts"; import { generationContentPatch } from "../canvas/generationReferenceContent.ts"; +import { audioTaskParameters } from "../canvas/audioTask.ts"; import { assemblyResource, staleAssembly } from "../canvas/editorAssembly.ts"; import { RULE_FACTS } from "../contracts/ruleFacts.generated.ts"; import { canvasReferenceFrameTime, canvasReferenceRole, MUSIC_SECONDS } from "./rules.ts"; @@ -900,6 +901,11 @@ export class CreationProjection { voiceSelection: spec.parameters.voiceSelection ?? undefined, audioCreationType: spec.parameters.creationType, audioMode: spec.parameters.mode, + audioTask: spec.parameters.taskType, + targetLanguage: spec.parameters.targetLanguage ?? undefined, + sourceLanguage: spec.parameters.sourceLanguage ?? undefined, + subtitleAssetId: + spec.parameters.subtitleAssetId ?? undefined, ...(spec.parameters.creationType === "music" ? { lyrics: spec.parameters.lyrics, @@ -1144,6 +1150,7 @@ export class CreationProjection { : {}), creationType: node.data.settings?.audioCreationType ?? "audio", mode: node.data.settings?.audioMode ?? "tts", + ...audioTaskParameters(node.data.settings ?? {}), ...(node.data.settings?.audioCreationType === "music" ? { lyrics: node.data.settings.lyrics ?? "", diff --git a/src/backend/rules.ts b/src/backend/rules.ts index 10c2c9d66..eb424bcfb 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -17,6 +17,7 @@ import { subjectReferenceNodes } from "../canvas/subjectReferences.ts"; export { subjectReferenceNodes } from "../canvas/subjectReferences.ts"; import { frameImageLimitIssue } from "../canvas/frameReferences.ts"; import { nodeDownstreamKinds } from "../canvas/connectionPolicy.ts"; +import { chosenAudioTask, declaredAudioTasks } from "../canvas/audioTask.ts"; import { tNow } from "../i18n/messages.ts"; import type { MessageKey } from "../i18n/types.ts"; import type { ModelAvailability } from "../contracts/generated.ts"; @@ -159,10 +160,21 @@ export function serviceAudioSettings( const unusable = unified || (!config.inputRules.voiceLibrary && Boolean(settings.voiceSelection)); + const tasks = declaredAudioTasks(config.inputRules.audioTasks); + const task = chosenAudioTask(settings, tasks); + const dubbing = task === "dubbing"; return { ...settings, audioCreationType: music ? "music" : "audio", audioMode: unified ? "unified" : "tts", + audioTask: tasks.length ? task : undefined, + ...(dubbing + ? {} + : { + targetLanguage: undefined, + sourceLanguage: undefined, + subtitleAssetId: undefined, + }), ...(unusable ? { voiceSelection: undefined, voiceName: undefined } : {}), ...(music && !(seconds >= MUSIC_SECONDS.min && seconds <= MUSIC_SECONDS.max) ? { durationSeconds: MUSIC_SECONDS.initial } @@ -626,6 +638,13 @@ export function backendBlocker( return tNow("errors.rules.transcriptionModel"); if (!isGenerationModel(config)) return tNow("errors.rules.segmentationModel"); + if ( + settings.mode === "audio" && + chosenAudioTask(settings, declaredAudioTasks(config.inputRules.audioTasks)) === + "dubbing" && + !settings.targetLanguage + ) + return tNow("generation.issue.audioTaskTarget"); const references = backendReferences(settings, [...incoming, ...pinned], config); const imageCount = references.filter((ref) => ref.node.data.kind === "image").length; const profile = settings.mode === "audio" ? (isMusicModel(config) ? "lyrics_to_music" : "text_to_speech") diff --git a/src/canvas/NodeComposer.tsx b/src/canvas/NodeComposer.tsx index 234d62b29..6d9231a41 100644 --- a/src/canvas/NodeComposer.tsx +++ b/src/canvas/NodeComposer.tsx @@ -60,6 +60,14 @@ import { type ModelConfig, } from "../backend/rules.ts"; import { resolveGenerationModel } from "./modelResolution.ts"; +import { + AUDIO_TASKS, + DUBBING_LANGUAGES, + chosenAudioTask, + declaredAudioTasks, + needsTargetLanguage, + subtitleChoices, +} from "./audioTask.ts"; import { GenerationComposerShell } from "./GenerationComposerShell"; import { useI18n } from "../i18n/I18nProvider"; import { @@ -105,6 +113,12 @@ export interface NodeComposerProps { /** Models configured in the local API, usable alongside the catalog. */ backendModels?: readonly ModelConfig[]; + projectAssets?: readonly { + id: string; + name?: string; + kind?: string; + mimeType?: string; + }[]; onCheckModels?: (ids: readonly string[]) => Promise; removeWatermark?: boolean; referenceControls?: GenerationReferenceControls; @@ -150,6 +164,7 @@ export function NodeComposer({ running = false, imagePresets = [], backendModels = [], + projectAssets = [], onCheckModels, removeWatermark = false, referenceControls, @@ -410,6 +425,10 @@ export function NodeComposer({ !music && !config?.inputRules.audioTasks?.length && (backend || settings.audioMode === "tts"); + const audioTasks = mode === "audio" ? declaredAudioTasks(config?.inputRules.audioTasks) : []; + const audioTask = chosenAudioTask(settings, audioTasks); + const dubbing = audioTasks.length > 0 && audioTask === "dubbing"; + const subtitles = dubbing ? subtitleChoices(projectAssets) : []; // YuE2-style music models can follow one connected recording. const musicReferences = music && Boolean(config?.inputRules.allowedKinds.includes("audio")); @@ -1243,6 +1262,93 @@ export function NodeComposer({ )} )} + {mode === "audio" && audioTasks.length > 1 && ( + + )} + {dubbing && ( + <> + + + {subtitles.length > 0 && ( + + )} + + )} {mode === "audio" && backend && !music && diff --git a/src/canvas/audioTask.ts b/src/canvas/audioTask.ts new file mode 100644 index 000000000..d9616e568 --- /dev/null +++ b/src/canvas/audioTask.ts @@ -0,0 +1,119 @@ +import type { GenerationSettings } from "./model"; + +export const AUDIO_TASKS = [ + "text2audio", + "dubbing", + "separation", + "reference", +] as const; +export type AudioTask = (typeof AUDIO_TASKS)[number]; + +export const DUBBING_LANGUAGES = [ + "zh", + "en", + "ja", + "ko", + "es", + "fr", + "de", + "it", + "pt", + "ru", + "ar", + "th", + "vi", + "id", + "ms", + "tr", + "hi", +] as const; +export type DubbingLanguage = (typeof DUBBING_LANGUAGES)[number]; + +export const SUBTITLE_MIME = "application/x-subrip"; + +const known = new Set(AUDIO_TASKS); +const languages = new Set(DUBBING_LANGUAGES); + +export function declaredAudioTasks(declared?: readonly string[]): AudioTask[] { + return (declared ?? []).filter((task): task is AudioTask => known.has(task)); +} + +export function chosenAudioTask( + settings: Partial, + declared?: readonly string[], +): AudioTask { + if (declared === undefined) return settings.audioTask ?? "text2audio"; + const available = declaredAudioTasks(declared); + if (!available.length) return "text2audio"; + const chosen = settings.audioTask; + return chosen && available.includes(chosen) ? chosen : available[0]; +} + +export interface AudioTaskParameters { + taskType?: AudioTask; + targetLanguage?: DubbingLanguage; + sourceLanguage?: DubbingLanguage; + subtitleAssetId?: string; +} + +export function audioTaskParameters( + settings: Partial, + declared?: readonly string[], +): AudioTaskParameters { + const task = chosenAudioTask(settings, declared); + if (task === "text2audio") return {}; + const target = + settings.targetLanguage && languages.has(settings.targetLanguage) + ? { targetLanguage: settings.targetLanguage as DubbingLanguage } + : {}; + const source = + settings.sourceLanguage && languages.has(settings.sourceLanguage) + ? { sourceLanguage: settings.sourceLanguage as DubbingLanguage } + : {}; + const subtitle = + settings.subtitleAssetId && task === "dubbing" + ? { subtitleAssetId: settings.subtitleAssetId } + : {}; + return { + taskType: task, + ...(task === "dubbing" ? target : {}), + ...(task === "dubbing" ? source : {}), + ...subtitle, + }; +} + +export function needsTargetLanguage( + settings: Partial, + declared?: readonly string[], +): boolean { + return chosenAudioTask(settings, declared) === "dubbing"; +} + +export function needsSubtitle( + settings: Partial, + declared?: readonly string[], +): boolean { + return chosenAudioTask(settings, declared) === "dubbing"; +} + +export interface SubtitleChoice { + id: string; + name: string; +} + +export function subtitleChoices( + assets: readonly { + id: string; + name?: string; + kind?: string; + mimeType?: string; + }[], +): SubtitleChoice[] { + return assets + .filter( + (asset) => + asset.kind === "text" && + (asset.mimeType ?? "").toLowerCase().startsWith(SUBTITLE_MIME), + ) + .map((asset) => ({ id: asset.id, name: asset.name ?? asset.id })); +} diff --git a/src/canvas/dataBoundary.ts b/src/canvas/dataBoundary.ts index 9eaff66a9..e008660bb 100644 --- a/src/canvas/dataBoundary.ts +++ b/src/canvas/dataBoundary.ts @@ -1,4 +1,5 @@ import { validTimelineText } from "./timelineText.ts"; +import { DUBBING_LANGUAGES } from "./audioTask.ts"; import { RULE_FACTS } from "../contracts/ruleFacts.generated.ts"; import { parseImageCrop } from "./imageCrop.ts"; @@ -51,6 +52,10 @@ const SETTINGS_KEYS = [ "pinnedFrames", "audioCreationType", "audioMode", + "audioTask", + "targetLanguage", + "sourceLanguage", + "subtitleAssetId", "voiceName", "voiceSelection", "lyrics", @@ -134,6 +139,22 @@ export function isGenerationSettings( (value.audioMode === undefined || value.audioMode === "unified" || value.audioMode === "tts") && + (value.audioTask === undefined || + value.audioTask === "text2audio" || + value.audioTask === "dubbing" || + value.audioTask === "separation" || + value.audioTask === "reference") && + (value.targetLanguage === undefined || + (typeof value.targetLanguage === "string" && + DUBBING_LANGUAGES.includes( + value.targetLanguage as (typeof DUBBING_LANGUAGES)[number], + ))) && + (value.sourceLanguage === undefined || + (typeof value.sourceLanguage === "string" && + DUBBING_LANGUAGES.includes( + value.sourceLanguage as (typeof DUBBING_LANGUAGES)[number], + ))) && + (value.subtitleAssetId === undefined || nonempty(value.subtitleAssetId)) && optionalString(value.voiceName) && (value.voiceSelection === undefined || (record(value.voiceSelection) && diff --git a/src/canvas/model.ts b/src/canvas/model.ts index 040d4cdf1..4d07ec1ca 100644 --- a/src/canvas/model.ts +++ b/src/canvas/model.ts @@ -73,6 +73,10 @@ export interface GenerationSettings { pinnedFrames?: { nodeId: string; seconds: number }[]; audioCreationType?: "audio" | "music"; audioMode?: "unified" | "tts"; + audioTask?: "text2audio" | "dubbing" | "separation" | "reference"; + targetLanguage?: string; + sourceLanguage?: string; + subtitleAssetId?: string; voiceName?: string; voiceSelection?: VoiceSelection; /** Music models: words to sing; empty asks for an instrumental piece. */ diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index 232f80f3e..e3265ce9d 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -2088,6 +2088,14 @@ export function WorkspaceView({ rt, editingState, editSession }: { imagePresets={imagePresetsFromFields( toolCatalog.capabilities["image-presets"]?.fields, )} + projectAssets={creationClient(doc.id).snapshot.assets.map( + (asset) => ({ + id: asset.id, + name: asset.name, + kind: asset.kind, + mimeType: asset.metadata.mimeType, + }), + )} pinnedPrecheck={pinnedPrecheckNodes({ node: composerNode, incoming: composerIncoming, diff --git a/src/i18n/messages/en-US/generation.ts b/src/i18n/messages/en-US/generation.ts index fc50e39e5..e0f1fb3e5 100644 --- a/src/i18n/messages/en-US/generation.ts +++ b/src/i18n/messages/en-US/generation.ts @@ -77,6 +77,35 @@ export const generation = { "generation.audioMode": "Audio mode", "generation.audioMode.unified": "Universal voice", "generation.audioMode.tts": "Text to speech", + "generation.issue.audioTaskTarget": "Choose the dubbing language", + "generation.audioTask": "Audio operation", + "generation.audioTask.text2audio": "Speech", + "generation.audioTask.dubbing": "Video dubbing", + "generation.audioTask.separation": "Track separation", + "generation.audioTask.reference": "Voice reference", + "generation.dubbing.targetLanguage": "Target language", + "generation.dubbing.targetLanguagePlaceholder": "Choose the dubbing language", + "generation.dubbing.sourceLanguage": "Source language", + "generation.dubbing.sourceLanguagePlaceholder": "Detected automatically", + "generation.dubbing.subtitle": "Subtitle file", + "generation.dubbing.subtitlePlaceholder": "Detected from the video", + "generation.language.zh": "Chinese", + "generation.language.en": "English", + "generation.language.ja": "Japanese", + "generation.language.ko": "Korean", + "generation.language.es": "Spanish", + "generation.language.fr": "French", + "generation.language.de": "German", + "generation.language.it": "Italian", + "generation.language.pt": "Portuguese", + "generation.language.ru": "Russian", + "generation.language.ar": "Arabic", + "generation.language.th": "Thai", + "generation.language.vi": "Vietnamese", + "generation.language.id": "Indonesian", + "generation.language.ms": "Malay", + "generation.language.tr": "Turkish", + "generation.language.hi": "Hindi", "generation.duration": "Video duration", "generation.duration.choose": "Choose video duration", "generation.duration.default": "Service default", diff --git a/src/i18n/messages/zh-CN/generation.ts b/src/i18n/messages/zh-CN/generation.ts index cdd5a1462..496ba209f 100644 --- a/src/i18n/messages/zh-CN/generation.ts +++ b/src/i18n/messages/zh-CN/generation.ts @@ -73,6 +73,35 @@ export const generation = { "generation.audioMode": "音频创作模式", "generation.audioMode.unified": "全能配音", "generation.audioMode.tts": "文本朗读", + "generation.issue.audioTaskTarget": "请选择配音语言", + "generation.audioTask": "音频操作", + "generation.audioTask.text2audio": "语音生成", + "generation.audioTask.dubbing": "视频重配音", + "generation.audioTask.separation": "分轨", + "generation.audioTask.reference": "音色参考", + "generation.dubbing.targetLanguage": "目标语言", + "generation.dubbing.targetLanguagePlaceholder": "选择配音语言", + "generation.dubbing.sourceLanguage": "原始语言", + "generation.dubbing.sourceLanguagePlaceholder": "自动检测", + "generation.dubbing.subtitle": "字幕文件", + "generation.dubbing.subtitlePlaceholder": "从视频识别", + "generation.language.zh": "中文", + "generation.language.en": "英语", + "generation.language.ja": "日语", + "generation.language.ko": "韩语", + "generation.language.es": "西班牙语", + "generation.language.fr": "法语", + "generation.language.de": "德语", + "generation.language.it": "意大利语", + "generation.language.pt": "葡萄牙语", + "generation.language.ru": "俄语", + "generation.language.ar": "阿拉伯语", + "generation.language.th": "泰语", + "generation.language.vi": "越南语", + "generation.language.id": "印度尼西亚语", + "generation.language.ms": "马来语", + "generation.language.tr": "土耳其语", + "generation.language.hi": "印地语", "generation.duration": "视频生成时长", "generation.duration.choose": "选择视频生成时长", "generation.duration.default": "服务默认时长", diff --git a/tests/audioTask.test.ts b/tests/audioTask.test.ts new file mode 100644 index 000000000..10e981fd1 --- /dev/null +++ b/tests/audioTask.test.ts @@ -0,0 +1,129 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + audioTaskParameters, + chosenAudioTask, + declaredAudioTasks, + subtitleChoices, +} from "../src/canvas/audioTask.ts"; +import { serviceAudioSettings, backendBlocker, type ModelConfig } from "../src/backend/rules.ts"; +import { setActiveLocale } from "../src/i18n/messages.ts"; + +const seedAudio = ( + tasks: ( + | "text2audio" + | "reference" + | "separation" + | "dubbing" + )[], +): ModelConfig => ({ + id: crypto.randomUUID(), + kind: "audio", + url: "http://127.0.0.1:8010/v1", + modelId: "doubao-seed-audio-1-5-261128", + connectionType: "self_hosted", + protocol: "volcengine", + authMode: "none", + inputRules: { + profile: "seed-audio", + allowedKinds: ["image", "audio", "video"], + maxImages: 1, + maxVideos: 1, + maxAudios: 6, + videoModes: [], + audioTasks: tasks, + outputFormats: ["mp3", "wav"], + }, +}); + +const dubbing = { + mode: "audio" as const, + model: "", + aspectRatio: "auto", + durationSeconds: 0, + resolution: "auto", + prompt: "Dub the speech into the target language.", + audioCreationType: "audio" as const, + audioMode: "unified" as const, + audioTask: "dubbing" as const, +}; + +test("a model only offers the operations it publishes, in its own order", () => { + assert.deepEqual(declaredAudioTasks(["dubbing", "text2audio", "unknown"]), [ + "dubbing", + "text2audio", + ]); + assert.deepEqual(declaredAudioTasks(undefined), []); + assert.equal(chosenAudioTask({}, ["separation", "dubbing"]), "separation"); + assert.equal(chosenAudioTask({ audioTask: "dubbing" }, ["separation"]), "separation"); + assert.equal(chosenAudioTask({ audioTask: "dubbing" }, []), "text2audio"); + assert.equal(chosenAudioTask({ audioTask: "dubbing" }), "dubbing"); +}); + +test("only dubbing asks the provider for a language and a subtitle", () => { + assert.deepEqual( + audioTaskParameters({ audioTask: "text2audio", targetLanguage: "en" }), + {}, + ); + assert.deepEqual( + audioTaskParameters({ audioTask: "separation", subtitleAssetId: "a" }), + { taskType: "separation" }, + ); + assert.deepEqual( + audioTaskParameters({ + audioTask: "dubbing", + targetLanguage: "en", + sourceLanguage: "zh", + subtitleAssetId: "subtitle", + }), + { + taskType: "dubbing", + targetLanguage: "en", + sourceLanguage: "zh", + subtitleAssetId: "subtitle", + }, + ); + assert.deepEqual(audioTaskParameters({ audioTask: "dubbing", targetLanguage: "xx" }), { + taskType: "dubbing", + }); +}); + +test("a project offers only its subtitle files for dubbing", () => { + assert.deepEqual( + subtitleChoices([ + { id: "1", name: "lines.srt", kind: "text", mimeType: "application/x-subrip" }, + { id: "2", name: "notes.txt", kind: "text", mimeType: "text/plain" }, + { id: "3", name: "clip.mp4", kind: "video", mimeType: "video/mp4" }, + ]), + [{ id: "1", name: "lines.srt" }], + ); +}); + +test("switching to a model without dubbing drops the language it collected", () => { + const settings = { ...dubbing, targetLanguage: "en", subtitleAssetId: "subtitle" }; + const kept = serviceAudioSettings(settings, seedAudio(["text2audio", "dubbing"])); + assert.equal(kept.audioTask, "dubbing"); + assert.equal(kept.targetLanguage, "en"); + assert.equal(kept.subtitleAssetId, "subtitle"); + const dropped = serviceAudioSettings(settings, seedAudio(["text2audio"])); + assert.equal(dropped.audioTask, "text2audio"); + assert.equal(dropped.targetLanguage, undefined); + assert.equal(dropped.subtitleAssetId, undefined); +}); + +test("dubbing waits for the language it has to translate into", () => { + setActiveLocale("zh-CN"); + const model = seedAudio(["text2audio", "dubbing"]); + const settings = serviceAudioSettings( + { ...dubbing, modelConfigId: model.id }, + model, + ); + assert.match(backendBlocker(settings, [], [model])!, /配音语言/); + assert.equal( + backendBlocker({ ...settings, targetLanguage: "en" }, [], [model]), + null, + ); + setActiveLocale("en-US"); + assert.match(backendBlocker(settings, [], [model])!, /dubbing language/); + setActiveLocale("zh-CN"); +}); From 51de24a6140f7efc71a21d0d9037f16c1fcaa5dd Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 4 Dec 2026 18:33:51 +0800 Subject: [PATCH 44/58] [feat] canvas: name every artifact of a job in the version list A job delivers a primary output plus audio tracks and subtitles, and the version list showed those siblings as interchangeable versions. Adopting one would point the node at a file the job never adopted. node_versions now reports role, variant and track for each row, apply_node_version refuses a non-primary row with result_not_adoptable, and the dialog labels the side artifact and keeps the apply button off it. The subtitle row stays out of an audio node because its kind differs. Ran: python3 -m pytest tests/test_result_artifacts.py (12 passed) Ran: node --test tests/artifactLabel.test.ts (1 passed) Ran: python3 -m pytest tests/test_creation_node_versions.py tests/test_seed_audio.py tests/test_agent_seed_audio.py tests/test_creation_workflow.py tests/test_localization.py (99 passed, 1 filelock flake that passes alone) --- .../application/creation_node_versions.py | 6 ++++ src/canvas/NodeVersionHistory.tsx | 21 ++++++++++++- src/canvas/artifactLabel.ts | 27 +++++++++++++++++ src/i18n/messages/en-US/canvasNodes.ts | 4 +++ src/i18n/messages/zh-CN/canvasNodes.ts | 4 +++ tests/artifactLabel.test.ts | 30 +++++++++++++++++++ tests/test_result_artifacts.py | 13 +++++++- 7 files changed, 103 insertions(+), 2 deletions(-) create mode 100644 src/canvas/artifactLabel.ts create mode 100644 tests/artifactLabel.test.ts diff --git a/packages/core/src/opendirector/application/creation_node_versions.py b/packages/core/src/opendirector/application/creation_node_versions.py index 30ba3cb68..7d27787f0 100644 --- a/packages/core/src/opendirector/application/creation_node_versions.py +++ b/packages/core/src/opendirector/application/creation_node_versions.py @@ -148,6 +148,9 @@ def node_versions(projects, project_id, item_id, *, assets): if key not in models: models[key] = available_model(projects, job.inputSnapshot.model) is not None rows.append(dict(asset=asset, source='generated' if job else asset.provenance.source, + role=getattr(parent, 'role', 'primary') if job else None, + variant=getattr(parent, 'variant', None) if job else None, + track=getattr(parent, 'track', None) if job else None, available=available, commandId=evidence['commandId'], resultId=evidence['result'].id if job else None, jobId=job.id if job else None, createdAt=job.createdAt if job else None, inputSnapshot=job.inputSnapshot if job else None, modelAvailable=models[key] if job else None, @@ -187,6 +190,9 @@ def apply_node_version(history, before, command, records): if blocking_version_jobs(before, item): raise ContractError('revision_conflict', '节点有未结束或待确认任务,请先处理任务。', item.id) job = evidence.get('job') + role = getattr(evidence.get('result'), 'role', 'primary') + if job is not None and role != 'primary': + raise ContractError('result_not_adoptable', '附加产物(音轨、字幕)不能替代主结果采用。', payload.asset.assetId) if job is None: if item.binding.role == 'generation': if item.kind != 'text' and not (item.kind == 'image' and asset.provenance.source == 'edited'): diff --git a/src/canvas/NodeVersionHistory.tsx b/src/canvas/NodeVersionHistory.tsx index cf3c6165e..2bd8106af 100644 --- a/src/canvas/NodeVersionHistory.tsx +++ b/src/canvas/NodeVersionHistory.tsx @@ -22,6 +22,7 @@ import "./generation-composer.css"; import "./node-editors.css"; import "./node-version-history.css"; import { useT } from "../i18n/I18nProvider.tsx"; +import { adoptableVersion, artifactDetail, artifactRoleKey } from "./artifactLabel.ts"; export interface NodeVersion { asset: Asset; @@ -32,6 +33,9 @@ export interface NodeVersion { currentReferencesDiffer: boolean; jobId: string | null; createdAt?: string | null; + role?: string | null; + variant?: string | null; + track?: string | null; } interface VersionListing { item: CanvasItem; @@ -483,10 +487,13 @@ export function NodeVersionHistory({ const label = t("canvasNodes.version.item", { index: index + 1 }); const select = () => { if (!busy) setSelected(version.asset.id); }; const isCurrent = version.asset.id === listing.currentAssetId; + const artifactRole = artifactRoleKey(version); + const artifactNote = artifactDetail(version); return (
)} + {artifactRole && ( +

+ {t(artifactRole)} + {artifactNote ? ` · ${artifactNote}` : ""} +

+ )}
); })} + {current && !adoptableVersion(current) && ( +

+ {t("canvasNodes.version.sideArtifact")} +

+ )} {(error || blockingJobIds.length > 0) && (

{error || t("canvasNodes.version.blockingJobs")} @@ -570,7 +588,8 @@ export function NodeVersionHistory({ title={video ? t("canvasNodes.version.hint") : undefined} disabled={ readOnly || busy || stale || blockingJobIds.length > 0 || - !current?.available || listing?.item.locked + !current?.available || listing?.item.locked || + !adoptableVersion(current ?? {}) } onClick={() => void apply()} > diff --git a/src/canvas/artifactLabel.ts b/src/canvas/artifactLabel.ts new file mode 100644 index 000000000..291259346 --- /dev/null +++ b/src/canvas/artifactLabel.ts @@ -0,0 +1,27 @@ +import type { MessageKey } from "../i18n/types.ts"; + +export interface ArtifactVersion { + role?: string | null; + variant?: string | null; + track?: string | null; +} + +const ROLES: Record = { + audio_track: "canvasNodes.version.artifact.audio_track", + subtitle: "canvasNodes.version.artifact.subtitle", + dubbed_video: "canvasNodes.version.artifact.dubbed_video", +}; + +export function artifactRoleKey(version: ArtifactVersion): MessageKey | null { + return version.role && version.role !== "primary" + ? (ROLES[version.role] ?? null) + : null; +} + +export function artifactDetail(version: ArtifactVersion): string { + return version.track ?? version.variant ?? ""; +} + +export function adoptableVersion(version: ArtifactVersion): boolean { + return !version.role || version.role === "primary"; +} diff --git a/src/i18n/messages/en-US/canvasNodes.ts b/src/i18n/messages/en-US/canvasNodes.ts index 0e40f8586..5238971e9 100644 --- a/src/i18n/messages/en-US/canvasNodes.ts +++ b/src/i18n/messages/en-US/canvasNodes.ts @@ -157,6 +157,10 @@ export const canvasNodes = { "canvasNodes.version.close": "Close version history", "canvasNodes.version.select": "Select a version", "canvasNodes.version.none": "This node has no versions yet.", + "canvasNodes.version.artifact.audio_track": "Audio track", + "canvasNodes.version.artifact.dubbed_video": "Dubbed video", + "canvasNodes.version.artifact.subtitle": "Subtitle", + "canvasNodes.version.sideArtifact": "This version is a side artifact. Only the adopted output can be applied to the node.", "canvasNodes.version.item": "Version {index}", "canvasNodes.version.current": "Current version", "canvasNodes.version.generationTime": "Generation started at", diff --git a/src/i18n/messages/zh-CN/canvasNodes.ts b/src/i18n/messages/zh-CN/canvasNodes.ts index 87a42eac3..56b7e7a5d 100644 --- a/src/i18n/messages/zh-CN/canvasNodes.ts +++ b/src/i18n/messages/zh-CN/canvasNodes.ts @@ -150,6 +150,10 @@ export const canvasNodes = { "canvasNodes.version.close": "关闭历史版本", "canvasNodes.version.select": "选择历史版本", "canvasNodes.version.none": "此节点暂无版本。", + "canvasNodes.version.artifact.audio_track": "音轨", + "canvasNodes.version.artifact.dubbed_video": "配音视频", + "canvasNodes.version.artifact.subtitle": "字幕", + "canvasNodes.version.sideArtifact": "该版本是附加产物,只有采用的主结果才能应用到节点。", "canvasNodes.version.item": "历史版本 {index}", "canvasNodes.version.current": "当前版本", "canvasNodes.version.generationTime": "发起生成的时间", diff --git a/tests/artifactLabel.test.ts b/tests/artifactLabel.test.ts new file mode 100644 index 000000000..163c6ea30 --- /dev/null +++ b/tests/artifactLabel.test.ts @@ -0,0 +1,30 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + adoptableVersion, + artifactDetail, + artifactRoleKey, +} from "../src/canvas/artifactLabel.ts"; + +test("a side artifact of one job is named, and only the primary is adopted", () => { + assert.equal(adoptableVersion({}), true); + assert.equal(adoptableVersion({ role: "primary" }), true); + assert.equal(adoptableVersion({ role: "audio_track" }), false); + assert.equal(adoptableVersion({ role: "dubbed_video" }), false); + + assert.equal(artifactRoleKey({}), null); + assert.equal(artifactRoleKey({ role: "primary" }), null); + assert.equal( + artifactRoleKey({ role: "audio_track" }), + "canvasNodes.version.artifact.audio_track", + ); + assert.equal( + artifactRoleKey({ role: "subtitle" }), + "canvasNodes.version.artifact.subtitle", + ); + assert.equal(artifactRoleKey({ role: "unrecorded" }), null); + + assert.equal(artifactDetail({ role: "audio_track", track: "speaker:0" }), "speaker:0"); + assert.equal(artifactDetail({ role: "subtitle", variant: "target_srt" }), "target_srt"); + assert.equal(artifactDetail({ role: "subtitle" }), ""); +}); diff --git a/tests/test_result_artifacts.py b/tests/test_result_artifacts.py index da8c9ce5a..6e78bf8ef 100644 --- a/tests/test_result_artifacts.py +++ b/tests/test_result_artifacts.py @@ -9,7 +9,7 @@ import pytest from opendirector.application.creation_assets import CreationAssets -from opendirector.application.creation_canvas import CreationCanvas +from opendirector.application.creation_canvas import CreationCanvas, asset_ref from opendirector.application.creation_history import CreationHistory from opendirector.application.creation_generation import CreationGeneration from opendirector.domain.assets import MAX_ASSET_BYTES @@ -277,6 +277,17 @@ async def test_a_track_is_offered_as_a_version_but_a_subtitle_is_not(project): assert (await runner.execute(command, session=session)).status == 'accepted' await settle(runner) assert [result.role for result in store.snapshot(pid).results] == ['primary', 'audio_track', 'subtitle'] + snapshot_results = store.snapshot(pid).results listing = CreationHistory(store).node_versions(pid, target.id) assert sorted(row['asset'].name for row in listing['versions']) == [ 'Say hello-audio_track-speaker-0.wav', 'Say hello.wav'] + assert {row['asset'].name: (row['role'], row['track']) for row in listing['versions']} == { + 'Say hello.wav': ('primary', None), + 'Say hello-audio_track-speaker-0.wav': ('audio_track', 'speaker:0')} + track = next(row for row in listing['versions'] if row['role'] == 'audio_track') + refused = send(store, pid, 'canvas.applyVersion', session=session, + versions=listing['expectedVersions'], itemId=target.id, + asset=asset_ref(track['asset']), + referencePolicy='follow_current') + assert refused.status == 'rejected' and refused.issues[0].code == 'result_not_adoptable' + assert store.snapshot(pid).results == snapshot_results From 85a30a45e3f3fa62ec4d8af52d2fcb8dc369879f Mon Sep 17 00:00:00 2001 From: Zhangbo-cn <60600082+Zhangbo-cn@users.noreply.github.com> Date: Sat, 5 Dec 2026 00:49:29 +0800 Subject: [PATCH 45/58] [feat] audio: complete Seed Audio 1.5 canvas, dubbing and re-voice flows - add operation, language, audited-SRT, voice and outputVideo inputs to the canvas audio composer, and play a video result in the node - list subtitle side artifacts separately so they stay reviewable without becoming adoptable node versions, and count the badge with the same filter as the version dialog - validate every SRT cue locally and report a refused input as an input failure with specific zh-CN/en-US guidance before any provider request - keep separation stem identity and mix a composite track, mux a playable re-voiced video, and record target/source subtitles from dubbing - document the user journey and the live verification receipts --- apps/api/src/opendirector_api/localization.py | 6 + docs/development/seed-audio-1-5-canvas.md | 67 ++++++ docs/development/seed-audio-1-5-probe.md | 52 +++-- .../application/creation_generation.py | 9 +- .../application/creation_history.py | 14 +- .../application/creation_node_versions.py | 18 +- .../application/generation_runtime.py | 11 +- .../domain/creation/generation.py | 9 + .../integrations/reference_inputs.py | 55 ++++- .../opendirector/integrations/seed_audio.py | 44 ++-- .../opendirector/integrations/volcengine.py | 37 +++- .../core/src/opendirector/media/processing.py | 31 +++ src/backend/creationProjection.ts | 1 + src/backend/rules.ts | 11 +- src/canvas/CanvasNodeView.tsx | 30 ++- src/canvas/NodeComposer.tsx | 48 ++++- src/canvas/NodeVersionHistory.tsx | 126 ++++++++++- src/canvas/artifactLabel.ts | 19 ++ src/canvas/audioTask.ts | 19 +- src/canvas/dataBoundary.ts | 3 + src/canvas/generationFailureText.ts | 24 +++ src/canvas/model.ts | 1 + src/canvas/node-version-history.css | 54 +++++ src/contracts/creation.schema.json | 24 +++ src/contracts/generated.ts | 4 + src/i18n/messages/en-US/canvasNodes.ts | 11 + src/i18n/messages/en-US/errors.ts | 20 ++ src/i18n/messages/en-US/generation.ts | 8 + src/i18n/messages/zh-CN/canvasNodes.ts | 11 + src/i18n/messages/zh-CN/errors.ts | 10 + src/i18n/messages/zh-CN/generation.ts | 8 + tests/artifactLabel.test.ts | 26 +++ tests/audioTask.test.ts | 19 ++ tests/backendRules.test.ts | 45 ++++ tests/generationFailureText.test.ts | 13 ++ tests/test_agent_seed_audio.py | 113 ++++++++++ tests/test_generation_errors.py | 26 +++ tests/test_result_artifacts.py | 6 + tests/test_seed_audio.py | 197 +++++++++++++++++- 39 files changed, 1161 insertions(+), 69 deletions(-) create mode 100644 docs/development/seed-audio-1-5-canvas.md diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 9d8d69c4a..cf3d17145 100644 --- a/apps/api/src/opendirector_api/localization.py +++ b/apps/api/src/opendirector_api/localization.py @@ -73,7 +73,13 @@ 'audio_separation_video': 'Track separation takes one audio input and no video.', 'audio_subtitle_scope': 'A subtitle file is used only when dubbing a referenced video.', 'audio_subtitle_asset': 'The subtitle must be an SRT file within the size limit.', + 'audio_subtitle_encoding': 'The subtitle file must use UTF-8 encoding.', + 'audio_subtitle_format': 'The subtitle must be valid SRT: each cue needs a start --> end timing line.', + 'audio_subtitle_order': 'Subtitle cue start times must increase in file order.', + 'audio_subtitle_range': 'The subtitle timeline must fall within the referenced video duration.', 'audio_subtitle_transport': 'A subtitle file needs a fetchable address: configure object storage before dubbing with subtitles.', + 'audio_voice_scope': 'Voice selection applies to speech or voice-reference generation only. Dubbing keeps the source voice and separation has no voice.', + 'audio_output_video_scope': 'A playable re-voiced video needs a referenced video with speech or voice-reference generation.', 'bigmodel_video_model': 'The BigModel video protocol supports CogVideoX-3 only.', 'bigmodel_video_output': 'Choose a supported CogVideoX-3 pixel size and a 5- or 10-second duration. The size determines the aspect ratio.', 'bigmodel_video_image': 'CogVideoX-3 frame images must be valid PNG or JPEG files, up to 5 MB each.', diff --git a/docs/development/seed-audio-1-5-canvas.md b/docs/development/seed-audio-1-5-canvas.md new file mode 100644 index 000000000..bd6a19caf --- /dev/null +++ b/docs/development/seed-audio-1-5-canvas.md @@ -0,0 +1,67 @@ +# Seed Audio 1.5 user journey and canvas design + +This document defines how Seed Audio 1.5 is used from the canvas and the agent. +It accompanies the adapter probe in +[`seed-audio-1-5-probe.md`](seed-audio-1-5-probe.md) and the implementation in +`seed_audio.py`, `reference_inputs.py` and the canvas audio composer. + +## 1. User journey + +| Step | User goal | Canvas behaviour | Failure and recovery | +| --- | --- | --- | --- | +| Input | Choose the picture and voice material | Add an audio node; connect at most one video, one image or one to four audio references; type the spoken lines in quotes; pick an audited SRT when dubbing by script | Mixed reference kinds are refused with a bilingual message before a job is created | +| Decide | Pick the operation and language | Audio operation select: 语音生成 / 视频重配音 / 分轨; dubbing shows target and source language plus an SRT picker; text/voice generation shows a preset editor and "可播放配音成片" when a video is referenced | A missing target language, a subtitle without a video, or a voice on dubbing is refused at the spec boundary | +| Generate | Start one job | `generation.submit` stores the concrete input snapshot (operation, languages, subtitle, voice, output video) with the job | A rejected submission leaves a readable issue in the node; the draft stays editable | +| Review | See every result in one place | The node shows the playable video when the result is video; the version badge opens the history dialog; side artifacts (target/source SRT and JSONL) are listed under "附件产物" with per-file preview | A failed download keeps the job in recovery/review instead of inventing a result | +| Adopt | Make a result the node's current output | "应用到当前节点" restores the job's prompt, references and parameters; side artifacts cannot replace the primary output | An unfinished job blocks application and offers to stop it | +| Continue | Reopen and keep working | Jobs, results, languages and provenance persist in the project snapshot; the timeline can take the independent track or the playable video | Reopening the same project shows the same artifacts and their producing job | + +## 2. Canvas prototype (walkable) + +1. **Audio node composer** — a Seed Audio service shows the operation select. + - `视频重配音` reveals target language, optional source language and the SRT + picker (only assets with `application/x-subrip`). + - `分轨` hides languages, subtitles and voices. + - `语音生成` / `参考生音频` show the voice input with the measured preset list + and a "可播放配音成片" toggle when a video is connected. +2. **Result card** — an audio node whose current asset is a video renders a + playable video card instead of a waveform, with a duration reported back to + the node metadata. +3. **Version history** — the dialog lists adoptable versions (primary results + and matching-kind tracks), the current result first; each row is labelled by + role, track or subtitle scope and target language. A footer button opens the + non-adoptable side artifacts, each expanding to its SRT/JSONL text. +4. **Timeline** — the independent track or dubbed video can be placed and + reused like any other canvas result. + +## 3. Project workflow + +- One video node can produce several language jobs. Each job records + `targetLanguage` on its results, and every version of the audio node shows + the language, so 英语 / 日本語 / 한국어 versions remain distinguishable. +- Subtitles are stored as ordinary project assets with provenance linking back + to the job. They are deliberately not adoptable node versions (a subtitle is + not an audio output), which is why the version list and the version badge + both exclude them while the artifacts panel exposes them. +- Reopening a project reconstructs the same jobs, results and asset provenance + without calling the provider again. +- A language version can be retried independently; a retry creates a new job + and a new set of versions instead of mutating the earlier outcome. + +## 4. Verification notes + +- The version list and the version badge use the same filter; a 4-version node + with four subtitles shows badge 4, dialog "共 4 个版本" and + "附件产物(4)". +- The English UI was checked with a browser `en-US` locale: the dialog reads + "Side artifacts (4)" and each subtitle row shows "Target subtitles · + English". +- Target and source SRT files for the acceptance video each contain six cues, + with the last cue ending at 19.775 s in the 19.8 s film. +- A subtitle outside the video is refused locally and shown as an input + failure with the same specific guidance in both locales, not as a generic + provider failure. +- Automated coverage: `tests/audioTask.test.ts`, `tests/backendRules.test.ts`, + `tests/artifactLabel.test.ts`, `tests/generationFailureText.test.ts`, + `tests/test_generation_errors.py`, `tests/test_result_artifacts.py`, + `tests/test_seed_audio.py` and `tests/test_agent_seed_audio.py`. diff --git a/docs/development/seed-audio-1-5-probe.md b/docs/development/seed-audio-1-5-probe.md index 4c1bbc24d..7dc1560ee 100644 --- a/docs/development/seed-audio-1-5-probe.md +++ b/docs/development/seed-audio-1-5-probe.md @@ -40,24 +40,52 @@ transports and the result parsing. dubbed video plus tracks and subtitles, so a job stores every file it produced under `(role, variant, track)` in a single commit. The adopted output stays the primary one; `result.select` refuses to adopt a sibling, and the - job projection lists the rest. Which subtitle entries a live dubbing response - actually carries is still unverified, so a missing entry never fails a job - that delivered its video. + job projection lists the rest. A live dubbing response was observed carrying + both target and source SRT and JSONL; a response that omits one of them still + never fails a job that delivered its video. - The service is synchronous, so a failed submission has no task id to resume: the existing `submission_unknown → review` rule stays correct and nothing is resubmitted automatically. ## Scope of this adapter release -- Accepted: `text2audio` through the existing composer and the shared - `generation.submit` command, with `speechRate`, `loudnessRate`, `pitchRate`, - `outputFormat` and `sampleRate` fixed in the accepted job. -- The composer renders the operation mode only; the prosody offsets are - reachable through the command contract (and therefore the agent), not yet - through dedicated controls. -- Not accepted yet: track separation (`taskType=separation` is refused with - `audio_task_unsupported`), and custom voices beyond the reference-audio path. - Each needs a separate change, as the probe explains. +- Accepted operations: `text2audio`, `reference` (image, audio, video and + audio+video references), `dubbing` (voice-only or with an audited SRT), + `separation` and playable re-voiced videos (`outputVideo`). +- Dubbing accepts a target language and an optional source language, records + both in the accepted execution, and returns the dubbed video, independent + tracks plus target/source SRT and JSONL files. +- `separation` keeps the first provider stem's identity (`speaker:0`) and adds + a locally mixed `composite:0` track when the provider does not return one. +- Preset voices use `speaker://`; registered Files voices use `file://`. The + composer offers the measured preset list and accepts a registered voice ID. +- `outputVideo` muxes generated speech back onto the referenced video without + re-encoding the picture, so an audio node can show a playable result. +- Prosody offsets and sample rate remain reachable through the command + contract (and therefore the agent), not through dedicated controls. +- The SRT is validated locally before upload: UTF-8, timing lines, ordered + starts, end >= start and every cue inside the referenced video. A refused + subtitle is reported as an input failure with specific bilingual guidance, + before any provider request. + +## Live verification on 2026-12-05 + +Every row is a fresh `generation.submit` through the business service, using +model `doubao-seed-audio-1-5-261128` and the 19.8 s acceptance video. + +| Scenario | Parameters | Result | +| --- | --- | --- | +| English translation | `taskType=dubbing`, `targetLanguage=en` | video 19.876 s, composite track 19.776 s, six English target cues and six Chinese source cues | +| Japanese version | same source video, `targetLanguage=ja` | video 19.876 s, six Japanese cues; リーマン予想 / 100万ドル / 1/2の直線 | +| Korean version | same source video, `targetLanguage=ko` | video 19.876 s, six Korean cues; 리만 가설 / 100만 달러 / 1/2 선 | +| Audited SRT dubbing | `targetLanguage=en`, `subtitleAssetId` = approved SRT | returned target SRT matches the audited file cue for cue (the provider appends one trailing blank line); video and track durations match | +| Track separation | `taskType=separation` | `speaker:0`, `sfx:0`, `bgm:0` and a derived `composite:0`, all 19.8 s | +| Prompt 1 re-dub | `text2audio`, video reference, Prompt 1, `outputVideo=true` | full 2475-character prompt sent with the video; playable 19.767 s MP4 with the picture copied and generated speech muxed; 19.2–19.8 s tail measures −66.1 dB mean (silent ending); independent composite track preserved | + +The exact per-scenario receipts and media live outside the repository under +`/tmp/seed-evidence/scenarios`; the automated regressions are +`tests/test_seed_audio.py`, `tests/test_agent_seed_audio.py` and +`tests/test_result_artifacts.py`. ## Measured output matrix diff --git a/packages/core/src/opendirector/application/creation_generation.py b/packages/core/src/opendirector/application/creation_generation.py index 2053de074..459cf4ed0 100644 --- a/packages/core/src/opendirector/application/creation_generation.py +++ b/packages/core/src/opendirector/application/creation_generation.py @@ -228,6 +228,10 @@ def _parameters(self, spec, config, node, records): params['source_language'] = intent['sourceLanguage'] if intent.get('subtitleAssetId'): params['subtitleAssetId'] = str(intent['subtitleAssetId']) + if intent.get('voice'): + params['voice'] = intent['voice'] + if intent.get('outputVideo'): + params['output_video'] = True elif spec.kind == 'audio' and intent.get('voice'): params['voice' if config['protocol'] == 'openai' else 'speaker'] = intent['voice'] if spec.kind == 'video': @@ -313,7 +317,8 @@ def _execution(kind, parameters, config): scoreMode=parameters.get('score_mode'), seed=parameters.get('seed')) if kind == 'audio' and input_rules(config)['profile'] == 'seed-audio': return dict(kind=kind, taskType=parameters['taskType'], - outputKind='video' if parameters['taskType'] == 'dubbing' else None, + outputKind='video' if parameters['taskType'] == 'dubbing' or parameters.get('output_video') else None, + outputVideo=bool(parameters.get('output_video')), voice=parameters.get('voice'), format=parameters.get('output_format', 'mp3'), sampleRate=parameters.get('sample_rate'), speechRate=parameters.get('speech_rate'), loudnessRate=parameters.get('loudness_rate'), pitchRate=parameters.get('pitch_rate'), @@ -680,7 +685,7 @@ def apply(current, asset): if same_selection or own_batch: additional = self._additional_item(current, item, asset, current_job) result = ResultVersion(id=uuid5(job.id, 'result'), projectId=job.projectId, specId=spec.id, jobId=job.id, - asset=asset_ref(asset), inputFingerprint=job.inputFingerprint) + asset=asset_ref(asset), inputFingerprint=job.inputFingerprint, track=task.get('primaryTrack')) extra_results = tuple(ResultVersion(id=uuid5(job.id, f"result:{record['role']}:{record.get('variant') or ''}:{record.get('track') or ''}"), projectId=job.projectId, specId=spec.id, jobId=job.id, inputFingerprint=job.inputFingerprint, role=record['role'], variant=record.get('variant'), track=record.get('track'), diff --git a/packages/core/src/opendirector/application/creation_history.py b/packages/core/src/opendirector/application/creation_history.py index df7c1c242..d4ed257f4 100644 --- a/packages/core/src/opendirector/application/creation_history.py +++ b/packages/core/src/opendirector/application/creation_history.py @@ -291,12 +291,18 @@ def version_counts(self, project_id): if spec_id is not None: owners.setdefault(spec_id, set()).add(item_id) jobs = {j.id: j for j in snapshot.jobs} + assets = {a.id: a for a in snapshot.assets} + kinds = {i.id: i.kind for i in snapshot.canvasItems if i.id in families} for result in snapshot.results: - for item_id in owners.get(result.specId, set()) | {jobs[result.jobId].originItemId}: - if item_id in families: + parents = owners.get(result.specId, set()) | {jobs[result.jobId].originItemId} + asset = assets.get(result.asset.assetId) + for item_id in parents: + # node_versions lists a side artifact only when its kind matches + # the node (subtitles never are), so the badge counts the same rows. + if item_id in families and asset is not None and ( + result.role == 'primary' or asset.kind == kinds[item_id]): families[item_id].add(result.asset.assetId) - assets = {a.id for a in snapshot.assets} - return dict(eventCursor=snapshot.eventCursor, counts={str(key): len(value & assets) for key, value in families.items()}) + return dict(eventCursor=snapshot.eventCursor, counts={str(key): len(value & assets.keys()) for key, value in families.items()}) def node_versions(self, project_id, item_id): from opendirector.application.creation_node_versions import node_versions diff --git a/packages/core/src/opendirector/application/creation_node_versions.py b/packages/core/src/opendirector/application/creation_node_versions.py index 7d27787f0..d441ca275 100644 --- a/packages/core/src/opendirector/application/creation_node_versions.py +++ b/packages/core/src/opendirector/application/creation_node_versions.py @@ -123,14 +123,12 @@ def node_versions(projects, project_id, item_id, *, assets): family = version_family(item, snapshot, indexed_bindings(facts)) read_media = assets.snapshot_media_reader(snapshot, resolved_path=path) if item.kind != 'video' else None models = {} - rows = [] + rows, artifacts = [], [] for asset in reversed(snapshot.assets): evidence = family.get(asset.id) if evidence is None: continue parent = evidence.get('result') - if parent is not None and parent.role != 'primary' and asset.kind != item.kind: - continue asset_id = asset.id available = True try: @@ -147,16 +145,24 @@ def node_versions(projects, project_id, item_id, *, assets): key = job.inputSnapshot.model.model_dump_json() if key not in models: models[key] = available_model(projects, job.inputSnapshot.model) is not None - rows.append(dict(asset=asset, source='generated' if job else asset.provenance.source, + row = dict(asset=asset, source='generated' if job else asset.provenance.source, role=getattr(parent, 'role', 'primary') if job else None, variant=getattr(parent, 'variant', None) if job else None, track=getattr(parent, 'track', None) if job else None, available=available, commandId=evidence['commandId'], resultId=evidence['result'].id if job else None, jobId=job.id if job else None, createdAt=job.createdAt if job else None, inputSnapshot=job.inputSnapshot if job else None, + targetLanguage=getattr(job.inputSnapshot.spec.parameters, 'targetLanguage', None) if job else None, modelAvailable=models[key] if job else None, - currentReferencesDiffer=bool(job and not evidence['retained'] and current_references_differ(snapshot, job.inputSnapshot)))) + currentReferencesDiffer=bool(job and not evidence['retained'] and current_references_differ(snapshot, job.inputSnapshot))) + if parent is not None and parent.role != 'primary' and asset.kind != item.kind: + # Side artifacts such as subtitles cannot replace the node output, + # but the history dialog still lists them for review. + row['inputSnapshot'] = None + artifacts.append(row) + else: + rows.append(row) current = current_asset(snapshot, item) - return deepcopy(dict(item=item, versions=rows, currentAssetId=current.id if current else None, + return deepcopy(dict(item=item, versions=rows, artifacts=artifacts, currentAssetId=current.id if current else None, blockingJobIds=blocking_version_jobs(snapshot, item), eventCursor=snapshot.eventCursor, expectedVersions=[dict(objectType=kind, id=obj.id, revision=obj.revision) diff --git a/packages/core/src/opendirector/application/generation_runtime.py b/packages/core/src/opendirector/application/generation_runtime.py index 97e2c7123..e6a2faf15 100644 --- a/packages/core/src/opendirector/application/generation_runtime.py +++ b/packages/core/src/opendirector/application/generation_runtime.py @@ -246,8 +246,15 @@ async def result_ready(suffix, url): if task.get('externalTaskId'): details = details.model_copy(update={'message': task['error']}) else: - details = GenerationFailure(category='local' if stage in {'save', 'adopt'} else 'provider', stage=stage, - message=task['error'], suggestion='请检查本地项目、磁盘和采用状态,保留已有结果。' if stage in {'save', 'adopt'} else '请核对原任务和模型服务后再处理。') + # A 422 ProjectError is a local input refusal (for example an + # audited SRT outside the video), not a provider failure. + refused_input = stage not in {'save', 'adopt'} and getattr(failure, 'status', None) == 422 + details = GenerationFailure( + category='local' if stage in {'save', 'adopt'} else 'input' if refused_input else 'provider', + stage=stage, message=task['error'], + suggestion='请检查本地项目、磁盘和采用状态,保留已有结果。' if stage in {'save', 'adopt'} + else '请调整提示词、参数或参考素材后重新提交。' if refused_input + else '请核对原任务和模型服务后再处理。') task['errorDetails'] = details.model_dump(mode='json') except Exception: # Do not leak provider responses, signed download URLs or credentials. diff --git a/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index a0ad6595e..55e4a9b12 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -98,6 +98,9 @@ class AudioParameters(Contract): taskType: Literal['text2audio', 'reference', 'separation', 'dubbing'] = Field( default='text2audio', exclude_if=lambda value: value == 'text2audio', description='Audio operation; the adapter derives outgoing reference roles from it.') + outputVideo: bool = Field( + default=False, exclude_if=lambda value: value is False, + description='Mux speech generated from a video reference back onto that video as a playable re-voiced file.') speechRate: Annotated[int, Field(strict=True, ge=-50, le=100)] = Field( default=0, exclude_if=lambda value: value == 0, description='Speaking-rate percentage offset.') loudnessRate: Annotated[int, Field(strict=True, ge=-50, le=100)] = Field( @@ -126,6 +129,8 @@ def separation_shape(self): return self if self.subtitleAssetId is not None: raise ValueError('Separation takes no subtitle file') + if self.outputVideo: + raise ValueError('Separation returns audio tracks, not a video') for name in ('speechRate', 'loudnessRate', 'pitchRate'): if getattr(self, name): raise ValueError('Separation takes no speech, loudness or pitch adjustment') @@ -140,6 +145,8 @@ def dubbing_language(self): raise ValueError('Language selection applies to dubbing only') if self.subtitleAssetId is not None and self.taskType != 'dubbing': raise ValueError('A subtitle asset applies to dubbing only') + if self.outputVideo and self.taskType == 'dubbing': + raise ValueError('Dubbing already returns a video') return self @model_validator(mode='after') @@ -337,6 +344,8 @@ class AudioExecution(Contract): creationType: Literal['audio', 'music'] = Field(default='audio', exclude_if=lambda value: value == 'audio', description='Speech or music creation mode.') outputKind: Literal['audio', 'video'] | None = Field(default=None, exclude_if=lambda value: value is None, description='Media the provider delivers when it differs from the model kind, as a re-voiced video does.') + outputVideo: bool = Field(default=False, exclude_if=lambda value: value is False, + description='Whether the accepted intent muxed speech back onto its referenced video.') # Legacy, see AudioParameters.instrumental. instrumental: bool = Field(default=False, exclude_if=lambda value: value is False, description='Legacy explicit instrumental choice retained for stored records.') # A music model may end the piece earlier than this cap. diff --git a/packages/core/src/opendirector/integrations/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 4d76bf8b2..00d0c11bc 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -2,6 +2,7 @@ import base64 import hashlib import json +import re from opendirector.domain.input_rules import MAX_REFERENCES, input_rules from opendirector.domain.rule_facts import ( @@ -83,11 +84,50 @@ def reference_content(store, owner, message, *, manifest=None, overrides=None): return content +_SRT_TIMING = re.compile( + r'^\s*(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})\s*-->\s*' + r'(\d{1,2}):(\d{2}):(\d{2})[,.](\d{1,3})') + + +def subtitle_cues(data, duration_ms): + """Parse an SRT file so the provider never has to reject a range it cannot reach.""" + try: + text = data.decode('utf-8-sig') + except UnicodeDecodeError: + raise ProjectError('字幕文件需使用 UTF-8 编码。', 422, code='audio_subtitle_encoding') from None + cues = [] + for line in text.replace('\r\n', '\n').replace('\r', '\n').split('\n'): + match = _SRT_TIMING.match(line) + if not match: + continue + start = (int(match.group(1)) * 3_600_000 + int(match.group(2)) * 60_000 + + int(match.group(3)) * 1_000 + int(match.group(4).ljust(3, '0')[:3])) + end = (int(match.group(5)) * 3_600_000 + int(match.group(6)) * 60_000 + + int(match.group(7)) * 1_000 + int(match.group(8).ljust(3, '0')[:3])) + cues.append((start, end)) + if not cues: + raise ProjectError('字幕文件需为有效的 SRT,每条字幕需包含“开始 --> 结束”时间行。', 422, + code='audio_subtitle_format') + if any(end < start for start, end in cues): + raise ProjectError('字幕条目的结束时间不能早于开始时间。', 422, code='audio_subtitle_range') + if any(later[0] <= earlier[0] for earlier, later in zip(cues, cues[1:])): + raise ProjectError('字幕条目的开始时间必须按顺序递增。', 422, code='audio_subtitle_order') + if duration_ms is not None and max(end for _, end in cues) > duration_ms + 500: + raise ProjectError('字幕时间轴超出视频时长,请改用与该视频对应的 SRT。', 422, code='audio_subtitle_range') + return cues + + def seed_audio_references(store, task, rules, result, overrides): total_ms = 0 - operation = (task.get('parameters') or {}).get('taskType') + parameters = task.get('parameters') or {} + operation = parameters.get('taskType') dubbing = operation == 'dubbing' separating = operation == 'separation' + voice = parameters.get('voice') + if voice and operation not in {'text2audio', 'reference'}: + raise ProjectError('音色选择只用于文生音频或参考生音频;翻配沿用原片音色,分轨不选择音色。', 422, + code='audio_voice_scope') + output_video = bool(parameters.get('output_video')) low_ms, high_ms = SEED_AUDIO_SEPARATION_MS if separating else SEED_AUDIO_REFERENCE_MS budget_ms = SEED_AUDIO_SEPARATION_TOTAL_MS if separating else SEED_AUDIO_REFERENCE_TOTAL_MS result['audio_role'] = 'separate_audio' if separating else 'reference_audio' @@ -127,6 +167,7 @@ def seed_audio_references(store, task, rules, result, overrides): if len(result['videos']) >= rules['maxVideos']: raise ProjectError('Seed Audio 1.5 一次只能引用一段视频。', 422, code='audio_reference_count') result['videos'].append(data) + result['videoDurationMs'] = duration result['manifest'].append({**entry, 'role': 'dubbing_video' if dubbing else 'reference_video'}) else: raise ProjectError(f'“{meta["name"]}”:Seed Audio 1.5 不接受这个素材。', 422, code='audio_reference_mix') @@ -135,13 +176,17 @@ def seed_audio_references(store, task, rules, result, overrides): if not dubbing or not result['videos']: raise ProjectError('字幕文件只在翻配视频时使用。', 422, code='audio_subtitle_scope') data, meta = store.asset(task['projectId'], str(subtitle_id)) - text = data.decode('utf-8', 'replace') - if (meta.get('type') not in {'text/plain', 'application/x-subrip'} or len(data) > SEED_AUDIO_SUBTITLE_BYTES - or '-->' not in text): + if meta.get('type') not in {'text/plain', 'application/x-subrip'} or len(data) > SEED_AUDIO_SUBTITLE_BYTES: raise ProjectError('字幕文件需为不超过 2 MB 的 SRT。', 422, code='audio_subtitle_asset') + subtitle_cues(data, result.get('videoDurationMs')) result['subtitle'] = data result['manifest'].append({'assetId': meta['id'], 'fingerprint': meta['fingerprint'], 'kind': 'text', 'transmission': 'content', 'role': 'custom_subtitle'}) + if voice and len(result['audios']) >= rules['maxAudios']: + raise ProjectError(f'音色与参考音频合计最多 {rules["maxAudios"]} 段。', 422, code='audio_reference_count') + if output_video and not (result['videos'] and operation in {'text2audio', 'reference'}): + raise ProjectError('可播放配音成片需要引用一段视频,并选择文生音频或参考生音频。', 422, + code='audio_output_video_scope') if result['videos'] and result['images']: raise ProjectError('Seed Audio 1.5 的视频参考与图片参考不能同时使用。', 422, code='audio_reference_mix') if dubbing and result['audios']: @@ -171,7 +216,7 @@ def generation_references(store, task, config, *, complete=True, overrides=None) rules = input_rules({**config, 'kind': 'agent' if kind == 'text' else kind}) mode = task.get('videoMode', 'first_frame') prompt = project_content(task['promptContent'], speech=kind == 'audio')[0] if task.get('promptContent') is not None else task['prompt'] - result = {'prompt': prompt, 'images': [], 'imageRoles': [], 'audios': [], 'videos': [], 'manifest': [], 'subtitle': None, 'rules': rules, 'continueFrom': None, 'continueSize': None, 'control': None, 'guides': []} + result = {'prompt': prompt, 'images': [], 'imageRoles': [], 'audios': [], 'videos': [], 'manifest': [], 'subtitle': None, 'rules': rules, 'continueFrom': None, 'continueSize': None, 'control': None, 'guides': [], 'videoDurationMs': None} if kind == 'text': result['content'] = reference_content(store, task['projectId'], {'text': task['prompt'], 'content': task.get('promptContent'), 'assets': [{'id': asset_id} for asset_id in task['referenceIds']]}, manifest=result['manifest'], overrides=overrides) request_size(result['content'], rules['requestBytes']) diff --git a/packages/core/src/opendirector/integrations/seed_audio.py b/packages/core/src/opendirector/integrations/seed_audio.py index a6fb76151..182c78efa 100644 --- a/packages/core/src/opendirector/integrations/seed_audio.py +++ b/packages/core/src/opendirector/integrations/seed_audio.py @@ -11,9 +11,18 @@ def is_seed_audio(model_id): return isinstance(model_id, str) and model_id.startswith(MODEL_PREFIX) -def request_body(config, prompt, parameters, images=(), audios=(), audio_role='reference_audio', videos=()): +def voice_uri(voice): + """Ark selects a preset with speaker:// and a Files-registered voice with file://.""" + if voice.startswith(('speaker://', 'file://')): + return voice + return f'file://{voice}' if voice.startswith('file-') else f'speaker://{voice}' + + +def request_body(config, prompt, parameters, images=(), audios=(), audio_role='reference_audio', videos=(), voice=None): content = [{'type': 'text', 'text': prompt}] content.extend({'type': 'image_url', 'role': 'reference_image', 'image_url': {'url': image}} for image in images) + if voice: + content.append({'type': 'audio_url', 'role': audio_role, 'audio_url': {'url': voice_uri(voice)}}) content.extend({'type': 'audio_url', 'role': audio_role, 'audio_url': {'url': audio}} for audio in audios) content.extend({'type': 'video_url', 'role': 'reference_video', 'video_url': {'url': video}} for video in videos) body = {'model': config['modelId'], 'content': content, @@ -31,7 +40,7 @@ def dubbing_body(config, video_url, parameters, subtitle_url=None): if parameters.get('source_language'): config_body['source_language'] = parameters['source_language'] if subtitle_url: - config_body['custom_subtitle'] = {'url': subtitle_url} + config_body['custom_subtitle'] = {'url': subtitle_url, 'format': 'srt'} body = {'model': config['modelId'], 'content': [{'type': 'video_url', 'role': 'dubbing_video', 'video_url': {'url': video_url}}], @@ -51,8 +60,8 @@ def artifact_suffix(url, allowed, default): return suffix if suffix in allowed else default -def _tracks(entries, artifacts): - counts = {} +def _tracks(entries, artifacts, counts=None): + counts = {} if counts is None else counts for entry in entries or []: url = entry.get('url') if isinstance(entry, dict) else None if not isinstance(url, str) or not url: @@ -71,17 +80,20 @@ def dubbing_artifacts(value): raise ValueError('Seed Audio returned no dubbed video') artifacts = [('primary', video, artifact_suffix(video, {'mp4', 'mov', 'webm'}, 'mp4'), None, None)] _tracks(content.get('audios'), artifacts) - for entry in content.get('subtitles') or []: - url = entry.get('url') if isinstance(entry, dict) else None - if not isinstance(url, str) or not url: - raise ValueError('Seed Audio subtitle has no URL') - scope = 'source' if str(entry.get('source') or entry.get('type') or '').lower() == 'source' else 'target' - suffix = str(entry.get('format') or '').lower() or artifact_suffix(url, TEXT_SUFFIXES, 'srt') - artifacts.append(('subtitle', url, suffix, f'{scope}_{suffix}', None)) + for key, default_scope in (('subtitles', 'target'), ('subtitles_source', 'source')): + for entry in content.get(key) or []: + url = entry.get('url') if isinstance(entry, dict) else None + if not isinstance(url, str) or not url: + raise ValueError('Seed Audio subtitle has no URL') + scope = default_scope + if key == 'subtitles' and str(entry.get('source') or entry.get('type') or '').lower() == 'source': + scope = 'source' + suffix = str(entry.get('format') or '').lower() or artifact_suffix(url, TEXT_SUFFIXES, 'srt') + artifacts.append(('subtitle', url, suffix, f'{scope}_{suffix}', None)) return tuple(artifacts) -def audio_artifacts(value): +def audio_artifacts(value, *, separation=False): audios = (value.get('content') or {}).get('audios') if not isinstance(audios, list) or not audios: raise ValueError('Seed Audio returned no audio artifact') @@ -89,6 +101,10 @@ def audio_artifacts(value): url = first.get('url') if isinstance(first, dict) else None if not isinstance(url, str) or not url: raise ValueError('Seed Audio artifact has no URL') - artifacts = [('primary', url, artifact_suffix(url, AUDIO_SUFFIXES, 'mp3'), None, None)] - _tracks(audios[1:], artifacts) + # Separation answers with typed stems, and the first one is the adopted + # result. Keep its stem identity so the version list can label it too. + stem = first.get('type') if separation and isinstance(first.get('type'), str) and first['type'] else None + primary_track = f'{stem}:0' if stem else None + artifacts = [('primary', url, artifact_suffix(url, AUDIO_SUFFIXES, 'mp3'), None, primary_track)] + _tracks(audios[1:], artifacts, {stem: 1} if stem else None) return tuple(artifacts) diff --git a/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index 3cdcf3934..55f7f6fd6 100644 --- a/packages/core/src/opendirector/integrations/volcengine.py +++ b/packages/core/src/opendirector/integrations/volcengine.py @@ -22,6 +22,7 @@ dubbing_artifacts as seed_audio_dubbing_artifacts, dubbing_body as seed_audio_dubbing_body, request_body as seed_audio_body, video_type as seed_audio_video_type) from opendirector.integrations import tos_transfer +from opendirector.media import processing as media from opendirector.media.probe import require_ffprobe @@ -163,8 +164,8 @@ async def extra_ready(role, variant, track, suffix, url): suffix, data = await self.generate(config, task, submitted, result_ready=result_ready, extra_ready=extra_ready) if not extras: - return (GeneratedArtifact(suffix, data),) - produced = [GeneratedArtifact(suffix, data)] + return (GeneratedArtifact(suffix, data, track=task.get('primaryTrack')),) + produced = [GeneratedArtifact(suffix, data, track=task.get('primaryTrack'))] try: async with httpx.AsyncClient(event_hooks=MODEL_HTTP_HOOKS, transport=self.transport, timeout=httpx.Timeout(240, connect=15), follow_redirects=False) as client: @@ -178,6 +179,13 @@ async def extra_ready(role, variant, track, suffix, url): raise transport_failure('download') from None except (httpx.InvalidURL, ValueError, TypeError, KeyError, AttributeError): raise protocol_failure('download') from None + if (is_seed_audio(config['modelId']) and task.get('parameters', {}).get('taskType') == 'separation' + and not any((item.track or '').startswith('composite:') for item in produced)): + stems = [(item.data, item.suffix) for item in produced] + if len(stems) > 1: + produced.append(GeneratedArtifact( + 'mp3', await asyncio.to_thread(media.mix_audio, stems), + role='audio_track', track='composite:0')) return tuple(produced) async def generate(self, config, task, submitted, *, result_ready=None, extra_ready=None): @@ -277,19 +285,36 @@ async def query(): payload = seed_audio_body(config, prompt, task["parameters"], prepared['images'], prepared['audios'], audio_role=prepared.get('audio_role', 'reference_audio'), - videos=videos) + videos=videos, voice=task["parameters"].get('voice')) request_size(payload, prepared['rules']['requestBytes']) async with client.stream("POST", endpoint(config["url"], "/contents/generations"), headers=headers, json=payload) as response: value = json.loads(await bounded(response, stage=stage, secrets=secrets)) stage = 'download' - artifacts = seed_audio_artifacts(value) + separating = task["parameters"].get("taskType") == "separation" + artifacts = seed_audio_artifacts(value, separation=separating) + if separating: + task['primaryTrack'] = artifacts[0][4] + audio_suffix = payload['output_format'] + output_video = bool(task["parameters"].get('output_video')) + if output_video and not prepared['videos']: + raise ProjectError("可播放配音成片需要引用一段视频。", 422, code="audio_output_video_scope") + if output_video: + if extra_ready: + await extra_ready('audio_track', None, 'composite:0', audio_suffix, artifacts[0][1]) + audio = await self._download(client, artifacts[0][1], secrets=secrets) + muxed = await asyncio.to_thread(media.replace_audio, prepared['videos'][0], audio, + audio_suffix=audio_suffix) + url = await self._publish_media(config, task["id"], muxed, "mp4", "video/mp4", noun="视频") + if result_ready: + await result_ready('mp4', url) + return "mp4", muxed if result_ready: - await result_ready(payload['output_format'], artifacts[0][1]) + await result_ready(audio_suffix, artifacts[0][1]) if extra_ready: for role, url, extra_suffix, variant, track in artifacts[1:]: await extra_ready(role, variant, track, extra_suffix, url) - return payload['output_format'], await self._download(client, artifacts[0][1], secrets=secrets) + return audio_suffix, await self._download(client, artifacts[0][1], secrets=secrets) if kind == "audio": url = endpoint(config["url"], "/tts/unidirectional") headers = {"X-Api-Key": config["apiKey"], "X-Api-Resource-Id": "seed-tts-2.0", "X-Api-Request-Id": str(uuid4())} diff --git a/packages/core/src/opendirector/media/processing.py b/packages/core/src/opendirector/media/processing.py index 63b6615e6..1b1a671e1 100644 --- a/packages/core/src/opendirector/media/processing.py +++ b/packages/core/src/opendirector/media/processing.py @@ -383,6 +383,37 @@ def without_audio(source: Path, out: Path) -> bytes: return out.read_bytes() +def replace_audio(video: bytes, audio: bytes, *, audio_suffix='mp3') -> bytes: + """Mux generated speech onto an existing picture without re-encoding it.""" + with Workspace() as workspace: + picture = workspace.write('source.mp4', video) + track = workspace.write('track.' + audio_suffix, audio) + out = workspace.path / 'revoiced.mp4' + _run(['ffmpeg', '-v', 'error', '-y', '-i', str(picture), '-i', str(track), + '-map', '0:v:0', '-map', '1:a:0', '-c:v', 'copy', '-c:a', 'aac', '-b:a', '192k', + '-af', 'apad', '-shortest', '-movflags', '+faststart', str(out)]) + return out.read_bytes() + + +def mix_audio(clips: list) -> bytes: + """Sum separated stems into one audition track; inputs are (bytes, suffix) pairs.""" + if not clips: + raise ProjectError('没有可混合的音轨。', 422) + if len(clips) == 1: + return clips[0][0] + with Workspace() as workspace: + paths = [workspace.write(f'stem-{index}.{suffix}', data) + for index, (data, suffix) in enumerate(clips)] + out = workspace.path / 'composite.mp3' + arguments = ['ffmpeg', '-v', 'error', '-y'] + for path in paths: + arguments += ['-i', str(path)] + arguments += ['-filter_complex', f'amix=inputs={len(paths)}:duration=longest:normalize=1', + '-c:a', 'libmp3lame', '-q:a', '2', str(out)] + _run(arguments) + return out.read_bytes() + + def is_stereo_with_side(source: Path) -> bool: """Whether L-R carries sound, i.e. a centre-cancelling background estimate means anything.""" value = json.loads(_run(['ffprobe', '-v', 'error', '-select_streams', 'a:0', '-show_entries', 'stream=channels', '-of', 'json', str(source)], timeout=60)) diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index 90e35bdc0..d79b34007 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -902,6 +902,7 @@ export class CreationProjection { audioCreationType: spec.parameters.creationType, audioMode: spec.parameters.mode, audioTask: spec.parameters.taskType, + outputVideo: spec.parameters.outputVideo ?? undefined, targetLanguage: spec.parameters.targetLanguage ?? undefined, sourceLanguage: spec.parameters.sourceLanguage ?? undefined, subtitleAssetId: diff --git a/src/backend/rules.ts b/src/backend/rules.ts index cb176dcc8..8ebc91c90 100644 --- a/src/backend/rules.ts +++ b/src/backend/rules.ts @@ -162,17 +162,22 @@ export function serviceAudioSettings( // "the voice belongs to another service" and leave no control to replace it, // so drop it here rather than waiting for a model switch to do the same. const unified = Boolean(config.inputRules.audioTasks?.length); + const seedAudio = config.inputRules.profile === "seed-audio"; const unusable = - unified || + (unified && !seedAudio) || (!config.inputRules.voiceLibrary && Boolean(settings.voiceSelection)); const tasks = declaredAudioTasks(config.inputRules.audioTasks); const task = chosenAudioTask(settings, tasks); const dubbing = task === "dubbing"; + const voiceApplies = seedAudio && !dubbing && task !== "separation"; return { ...settings, audioCreationType: music ? "music" : "audio", audioMode: unified ? "unified" : "tts", audioTask: tasks.length ? task : undefined, + ...(dubbing || task === "separation" + ? { outputVideo: undefined } + : {}), ...(dubbing ? {} : { @@ -180,6 +185,10 @@ export function serviceAudioSettings( sourceLanguage: undefined, subtitleAssetId: undefined, }), + ...(seedAudio && + (!voiceApplies || !isServiceVoice(settings.voiceName)) + ? { voiceName: undefined } + : {}), ...(unusable ? { voiceSelection: undefined, voiceName: undefined } : {}), ...(music && !(seconds >= MUSIC_SECONDS.min && seconds <= MUSIC_SECONDS.max) ? { durationSeconds: MUSIC_SECONDS.initial } diff --git a/src/canvas/CanvasNodeView.tsx b/src/canvas/CanvasNodeView.tsx index adabc58b5..41c5c4f55 100644 --- a/src/canvas/CanvasNodeView.tsx +++ b/src/canvas/CanvasNodeView.tsx @@ -213,7 +213,35 @@ function CanvasNodeContents({ id, data, selected }: NodeProps) { } /> )} - {kind === "audio" && ( + {kind === "audio" && data.mimeType?.startsWith("video/") && ( + // Seed Audio can mux generated speech onto the reference video. + // Show that playable film in place of the waveform for the result. + + actions?.metadata(id, { + durationSeconds: event.currentTarget.duration, + }) + } + onLoadedMetadata={(event) => + actions?.metadata(id, { + width: event.currentTarget.videoWidth, + height: event.currentTarget.videoHeight, + durationSeconds: event.currentTarget.duration, + }) + } + /> + )} + {kind === "audio" && !data.mimeType?.startsWith("video/") && (

+ {storageNeeded && ( +
+ {t("models.service.storage")} +

+ {t( + storageConfigured + ? "models.service.storageConfiguredNote" + : "models.service.storageNote", + )} +

+
+ + + + +
+
+ )} {["minimax_video_v2", "kling_video", "bigmodel_video"].includes(value.protocol) && (

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

)} @@ -594,6 +726,7 @@ export function ModelServiceForm({