diff --git a/apps/api/src/opendirector_api/localization.py b/apps/api/src/opendirector_api/localization.py index 94914358a..c94c74953 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, @@ -57,6 +59,31 @@ '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, 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.', + '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.', + 'seed_audio_storage': 'This task needs media the provider can fetch. Configure the model account object storage first.', + 'seed_audio_storage_rejected': 'Object storage rejected the upload. Check the bucket, region and access keys.', + 'seed_audio_storage_timeout': 'The object storage upload timed out. Check the network and try again.', + 'seed_audio_storage_unreachable': 'Object storage could not be reached. Check the endpoint, network and proxy settings.', + '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.', @@ -189,6 +216,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/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 889dde41a..90429831b 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/docs/architecture/unified-project.md b/docs/architecture/unified-project.md index 411e0440c..6d30a8e0e 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 和后台完成写入共享可恢复变更通道。通知提示对象发生变化,查询返回权威状态;处理断线、重复和乱序,不能通过整页重载掩盖同步问题。 浏览器保存草稿、交互状态和可重建缓存。拖动中不逐指针写盘;按受影响对象更新,避免反复读取大媒体或全历史。冲突保留输入,视图保存失败与业务提交结果分别反馈。 @@ -150,6 +161,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, 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 for review and timeline use, though only the primary result can be adopted; one that does not match, such as a subtitle on an audio node, is not offered as a version. + 浏览器与后台的执行职责必须明确。Agent 可以修改时间线,不代表后台已经能够导出视频;只有存在可调用渲染服务并验证真实输出,才可声称支持关闭浏览器后的自主导出。浏览器合成也可以作为明确需要客户端参与的能力保留。 ### 动效编辑文档与后台渲染 / Motion documents and background rendering diff --git a/docs/development/lessons.md b/docs/development/lessons.md index 292eaf466..55927d759 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -196,6 +196,11 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **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. ## GUI-launched desktop apps do not inherit the user's shell PATH - **Trigger:** Launching the packaged desktop app from macOS Finder/Dock or a desktop launcher and probing an external CLI harness whose entry point uses `#!/usr/bin/env `. 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..826014404 --- /dev/null +++ b/docs/development/seed-audio-1-5-canvas.md @@ -0,0 +1,81 @@ +# 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 up to six audio references; type the spoken lines in quotes; pick an audited SRT when dubbing by script | The combinations the service rejects (image with audio or video, dubbing with extra audio) 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) + +### Account setup + +The `ark-content` preset uploads video and subtitle inputs to a TOS bucket the +provider can read. The model-service form shows an **Object storage** section +(Access Key, Secret Key, Bucket, Region) for this model. Filling all four +enables video dubbing, video references and playable re-voice uploads; speech +generation works without it. Reopening the service loads the saved bucket and +region, and blank key fields keep the stored credentials. + +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. + - `语音生成` shows the voice input with the measured preset list and a + "可播放配音成片" toggle when a video is connected; connected image, + audio and video nodes become references for the same operation. +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 versions (the primary result and + matching-kind tracks), the current result first; only the primary result can + be applied. 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. +- If the video downloads but one sibling artifact does not, retrying the job + resumes the primary and the recorded sibling locators without resubmitting + the provider request; the recovered artifacts are saved beside the primary. +- 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 new file mode 100644 index 000000000..3334c6212 --- /dev/null +++ b/docs/development/seed-audio-1-5-probe.md @@ -0,0 +1,117 @@ +# 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. +- **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 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. 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 input shapes: `text2audio` with one image, up to six audio + references, or one video (including 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 six presets, each answered with one audio artifact on + 2026-12-05, 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 + +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_assets.py b/packages/core/src/opendirector/application/creation_assets.py index 054cad5ce..2a7ada534 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,7 +137,7 @@ 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 @@ -150,12 +151,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 +182,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 d8c83cc9d..ca24ee4ec 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'}} @@ -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: @@ -774,6 +775,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 +827,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 +846,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} @@ -976,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 563550426..459cf4ed0 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) @@ -213,6 +213,25 @@ 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 = {'taskType': 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'] + if intent.get('targetLanguage'): + params['target_language'] = intent['targetLanguage'] + if intent.get('sourceLanguage'): + 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': @@ -296,6 +315,16 @@ 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['taskType'], + 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'), + targetLanguage=parameters.get('target_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') @@ -378,7 +407,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) @@ -416,7 +445,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: @@ -569,35 +598,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) + 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=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) + 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, primary_kind) 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): + 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=(), 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': + 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))) + 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) current_spec = next(s for s in current.generationSpecs if s.id == spec.id) @@ -635,7 +685,11 @@ 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'), + 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, @@ -648,13 +702,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/creation_history.py b/packages/core/src/opendirector/application/creation_history.py index df7c1c242..373bc3945 100644 --- a/packages/core/src/opendirector/application/creation_history.py +++ b/packages/core/src/opendirector/application/creation_history.py @@ -291,12 +291,16 @@ 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: + 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 7a27ba7b8..aae4aa03a 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 @@ -123,11 +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') asset_id = asset.id available = True try: @@ -144,13 +145,22 @@ 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: + 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) @@ -165,7 +175,11 @@ def read_version_media(history, before, payload, bindings): raise ContractError('reference_invalid', '该素材不属于此节点的历史版本。', payload.asset.assetId) assets = history.assets asset = assets._reference(before, payload.asset) - if asset.kind != item.kind: + job = evidence.get('job') + result = evidence.get('result') + playable = (item.kind == 'audio' and asset.kind == 'video' and job is not None + and job.inputSnapshot.spec.kind == 'audio' and getattr(result, 'role', 'primary') == 'primary') + if asset.kind != item.kind and not playable: raise ContractError('invalid_input', '历史素材类型与节点不匹配。', item.id) read_media = assets.snapshot_media_reader(before) stream, _ = read_media(asset.id) @@ -184,6 +198,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/packages/core/src/opendirector/application/generation_runtime.py b/packages/core/src/opendirector/application/generation_runtime.py index a9135ba40..76732ce1e 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', '') @@ -17,6 +18,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 @@ -99,6 +102,29 @@ def recovery(self, task, directory): return 'review' + async def _produce(self, config, task, submitted, result_ready, cache): + if hasattr(self.provider, 'generate_all'): + return tuple(await self.provider.generate_all(config, task, submitted, + result_ready=result_ready, recovery_cache=cache)) + if task.get('protocol') == 'higgsfield_open': + 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 _resume_artifacts(self, config, task, cache, primary): + if not hasattr(self.provider, 'resume_artifacts'): + return () + if await asyncio.to_thread(cache.artifacts): + return () + records = await asyncio.to_thread(cache.artifact_locators) + if not records: + return () + return await self.provider.resume_artifacts(config, task, records, primary=primary) + async def _run(self, task, pinned, config, mode='submit'): stage = 'save' cache = gateway().results(pinned, task['id']) @@ -155,6 +181,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) @@ -162,19 +189,17 @@ async def result_ready(suffix, url): stage = 'download' metadata = cache.metadata() suffix, data = await self.provider.resume_result(config, metadata['suffix'], metadata['url']) + extras = await self._resume_artifacts(config, task, cache, GeneratedArtifact(suffix, data)) else: 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 + extras = await self._resume_artifacts(config, task, cache, GeneratedArtifact(suffix, data)) # Preserve complete bytes before catalog/link writes. Cancellation # waits for local commit; recovery reconciles partial commits. with anyio.CancelScope(shield=True): @@ -182,9 +207,14 @@ async def result_ready(suffix, url): raise asyncio.CancelledError() self.committing.add(task["id"]) stage = 'save' - if asset is None and cached is None: + if asset is None and (cached is None or extras): 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]) + if cached is None: + await asyncio.to_thread(cache.save, suffix, data) 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) @@ -229,8 +259,13 @@ 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 '请核对原任务和模型服务后再处理。') + 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/commands.py b/packages/core/src/opendirector/domain/creation/commands.py index 124476e58..d05e398fe 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', @@ -604,6 +604,14 @@ 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', 'audio_dubbing_video', 'audio_dubbing_source', 'audio_separation_video', + 'audio_subtitle_scope', 'audio_subtitle_asset', 'audio_subtitle_transport', + 'audio_subtitle_encoding', 'audio_subtitle_format', 'audio_subtitle_order', 'audio_subtitle_range', + 'audio_voice_scope', 'audio_output_video_scope', + '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', @@ -615,7 +623,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): @@ -701,7 +709,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/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/packages/core/src/opendirector/domain/creation/generation.py b/packages/core/src/opendirector/domain/creation/generation.py index 89677c440..55e4a9b12 100644 --- a/packages/core/src/opendirector/domain/creation/generation.py +++ b/packages/core/src/opendirector/domain/creation/generation.py @@ -95,6 +95,59 @@ 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.') + 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( + 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.') + 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.') + 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.') + + @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') + 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') + return self + + @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') + if self.outputVideo and self.taskType == 'dubbing': + raise ValueError('Dubbing already returns a video') + return self @model_validator(mode='after') def voice_identity(self): @@ -274,7 +327,25 @@ 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.') + 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.') + 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.') + 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. @@ -330,7 +401,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') @@ -353,6 +425,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): @@ -491,6 +569,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 2cb59901f..9d62ba16b 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, @@ -107,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.') @@ -229,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.""" diff --git a/packages/core/src/opendirector/domain/creation/project.py b/packages/core/src/opendirector/domain/creation/project.py index 3d5e4e0a8..413d098f3 100644 --- a/packages/core/src/opendirector/domain/creation/project.py +++ b/packages/core/src/opendirector/domain/creation/project.py @@ -165,13 +165,20 @@ 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: + 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/domain/input_rules.py b/packages/core/src/opendirector/domain/input_rules.py index 81c47e6ff..90d77dd56 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 @@ -180,6 +181,12 @@ 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', 'video'], maxImages=1, maxAudios=6, + maxVideos=1, referencesAllowed=True, maxPromptCharacters=10000, + audioTasks=['text2audio', 'dubbing', 'separation'], + 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..a992ba680 100644 --- a/packages/core/src/opendirector/domain/rule_facts.py +++ b/packages/core/src/opendirector/domain/rule_facts.py @@ -10,6 +10,15 @@ """ 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 +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 TEXT_REFERENCE_BYTES = 64 * 1024 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/packages/core/src/opendirector/infrastructure/generation_results.py b/packages/core/src/opendirector/infrastructure/generation_results.py index a2516a494..ba410d0b1 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,27 @@ 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): + 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) + + +def _locator_url(url): + if not isinstance(url, str): + raise ValueError('Locator is not a URL.') + parts = urlsplit(url) + if (parts.scheme not in {'http', 'https'} or not parts.hostname + or parts.username or parts.password or len(url) > 16384): + raise ValueError('Locator is not a URL.') + return url + + class GenerationResults: def __init__(self, directory, task_id): self.root = child(Path(directory), '.generation-results') @@ -78,6 +100,90 @@ def data(self): raise ProjectError('生成恢复缓存超过大小限制。', 409) return metadata['suffix'], path.read_bytes() + def artifact_file(self, record): + return child(self.directory, f"artifact-{_artifact_key(record['role'], record.get('variant'), record.get('track'))}") + + def artifacts(self): + 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): + 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 artifact_locators(self): + path = child(self.directory, 'artifact-locators.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() + _locator_url(record.get('url')) + return tuple(records) + except (KeyError, TypeError, ValueError): + raise ProjectError('生成恢复缓存无效,请保留原文件并核对任务。', 409) from None + + def save_artifact_locators(self, records): + prepared = [] + for record in records: + identity = {'role': record.get('role'), 'variant': record.get('variant'), 'track': record.get('track'), + 'suffix': record.get('suffix'), 'url': record.get('url')} + if identity['suffix'] not in ARTIFACT_SUFFIXES: + raise ProjectError('生成产物的文件类型无法保存到项目。', 415) + try: + _artifact_key(identity['role'], identity['variant'], identity['track']) + _locator_url(identity['url']) + except ValueError: + raise ProjectError('生成产物的标识无效,无法保存到项目。', 409) from None + prepared.append({key: value for key, value in identity.items() if value is not None}) + self._prepare() + write_json(child(self.directory, 'artifact-locators.json'), {'artifacts': prepared}) + def save(self, suffix, data): if len(data) > MAX_ASSET_BYTES: raise ProjectError('生成结果超过 50 MB,无法保存到项目。', 413) @@ -102,7 +208,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', 'artifact-locators.json'): child(self.directory, name).unlink(missing_ok=True) for directory in (self.directory, self.root): try: diff --git a/packages/core/src/opendirector/infrastructure/model_configs.py b/packages/core/src/opendirector/infrastructure/model_configs.py index 9494704c4..0086b8498 100644 --- a/packages/core/src/opendirector/infrastructure/model_configs.py +++ b/packages/core/src/opendirector/infrastructure/model_configs.py @@ -16,6 +16,19 @@ 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, + 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, + code="model_storage_incomplete") + return merged class ModelConfigs: @@ -40,7 +53,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 +61,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 +148,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 +163,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 +207,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/packages/core/src/opendirector/integrations/providers.py b/packages/core/src/opendirector/integrations/providers.py index 37328115d..415362354 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,24 @@ from opendirector.media.probe import require_ffprobe +class GeneratedArtifact(NamedTuple): + + 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): + return ARTIFACT_KINDS.get(suffix) + + class GenerationProviders(VolcengineGeneration): """Protocol adapters, plus dedicated adapters for vLLM-Omni MiniMax-H3 and Z-Image-Turbo profiles.""" @@ -134,7 +153,15 @@ async def resume_result(self, config, suffix, url): except (httpx.InvalidURL, ValueError, TypeError, KeyError, AttributeError): raise protocol_failure('download') from None - async def generate(self, config, task, submitted, *, result_ready=None, recovery_cache=None): + async def generate_all(self, config, task, submitted, *, result_ready=None, recovery_cache=None): + 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, + 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': @@ -173,7 +200,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/reference_inputs.py b/packages/core/src/opendirector/integrations/reference_inputs.py index 1bb9c3af1..00d0c11bc 100644 --- a/packages/core/src/opendirector/integrations/reference_inputs.py +++ b/packages/core/src/opendirector/integrations/reference_inputs.py @@ -2,10 +2,12 @@ import base64 import hashlib import json +import re 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_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 from opendirector.domain.minimax_image import validate_minimax_image_reference @@ -82,6 +84,118 @@ 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 + 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' + 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 = 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 > 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': result['audio_role']}) + elif source_kind == 'video': + if separating: + raise ProjectError('分轨只接收一段音频,不支持视频。', 422, code='audio_separation_video') + duration = meta.get('durationMs') + low, high = SEED_AUDIO_DUBBING_MS + 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['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') + 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)) + 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']: + 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 + + 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 服务生成并已完成的视频,上传或其他模型生成的视频不能接续。' @@ -102,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': [], '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']) @@ -114,6 +228,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..8d71b4ab1 --- /dev/null +++ b/packages/core/src/opendirector/integrations/seed_audio.py @@ -0,0 +1,108 @@ +"""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) + + +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, + '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 dubbing_body(config, video_url, parameters, subtitle_url=None): + config_body = {'target_language': parameters['target_language']} + if parameters.get('source_language'): + config_body['source_language'] = parameters['source_language'] + if 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}}], + 'dubbing_config': config_body, + 'include': ['video_url', 'subtitles.srt', 'subtitles.jsonl', + 'subtitles_source.srt', 'subtitles_source.jsonl']} + 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 + + +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: + 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): + 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 = [('primary', video, artifact_suffix(video, {'mp4', 'mov', 'webm'}, 'mp4'), None, None)] + _tracks(content.get('audios'), artifacts) + 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, *, 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') + 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') + 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/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/packages/core/src/opendirector/integrations/volcengine.py b/packages/core/src/opendirector/integrations/volcengine.py index a3ee9c8b0..adff3bc05 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 @@ -16,6 +18,11 @@ 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 (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, 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 @@ -81,6 +88,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) @@ -141,7 +153,67 @@ 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): + from opendirector.integrations.providers import GeneratedArtifact + + extras = [] + + async def extra_ready(role, variant, track, suffix, url): + extras.append({'role': role, 'variant': variant, 'track': track, 'suffix': suffix, 'url': url}) + if recovery_cache is not None: + await asyncio.to_thread(recovery_cache.save_artifact_locators, list(extras)) + + suffix, data = await self.generate(config, task, submitted, result_ready=result_ready, + extra_ready=extra_ready) + if not extras: + return (GeneratedArtifact(suffix, data, track=task.get('primaryTrack')),) + produced = [GeneratedArtifact(suffix, data, track=task.get('primaryTrack'))] + produced.extend(await self._download_artifacts(config, extras)) + 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 _download_artifacts(self, config, records): + from opendirector.integrations.providers import GeneratedArtifact + + produced = [] + 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 record in records: + produced.append(GeneratedArtifact( + record['suffix'], await self._download(client, record['url'], secrets=(config['apiKey'],)), + role=record['role'], variant=record.get('variant'), track=record.get('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 produced + + async def resume_artifacts(self, config, task, records, *, primary=None): + from opendirector.integrations.providers import GeneratedArtifact + + if not records: + return () + produced = await self._download_artifacts(config, records) + if (primary is not None and 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 = [(primary.data, primary.suffix)] + [(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): kind = task["kind"] if kind == "text": return await self._text(config, task) @@ -203,6 +275,71 @@ 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": + if not prepared["videos"]: + raise ProjectError("翻配需要引用一段视频。", 422, code="audio_dubbing_source") + subtitle_url = None + if prepared.get("subtitle"): + if not self._storage_ready(config): + raise ProjectError("字幕文件需要可拉取的地址,请先配置对象存储后再提交翻配。", 422, + code="audio_subtitle_transport") + subtitle_url = await self._publish_media(config, task["id"], prepared["subtitle"], "srt", + "application/x-subrip", noun="字幕") + source = await self._publish_media(config, task["id"], prepared["videos"][0], "mp4", "video/mp4", + noun="视频") + 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: + value = json.loads(await bounded(response, stage=stage, secrets=secrets)) + stage = 'download' + artifacts = seed_audio_dubbing_artifacts(value) + if result_ready: + 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"]): + 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'), + 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' + 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(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 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())} @@ -234,6 +371,33 @@ async def query(): except (ValueError, TypeError, KeyError, IndexError, AttributeError): raise protocol_failure(stage) from None + def _storage_ready(self, config): + 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="素材"): + 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: + 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: + try: + os.unlink(path) + except OSError: + pass + 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: 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 8a63d3552..d79b34007 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,12 @@ export class CreationProjection { voiceSelection: spec.parameters.voiceSelection ?? undefined, 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: + spec.parameters.subtitleAssetId ?? undefined, ...(spec.parameters.creationType === "music" ? { lyrics: spec.parameters.lyrics, @@ -1144,6 +1151,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/models.ts b/src/backend/models.ts index d1f50f130..87e2ad208 100644 --- a/src/backend/models.ts +++ b/src/backend/models.ts @@ -65,6 +65,30 @@ export interface ModelConfigInput { videoCapabilities?: VideoCapabilities | null; } +export interface ModelStorageInput { + accessKey: string; + secretKey: string; + bucket: string; + region: string; +} + +export interface ModelStorageState { + bucket: string | null; + region: string | null; + configured: boolean; +} + +export function readModelStorage(configId: string) { + return request(`/model-services/${configId}/storage`); +} + +export function saveModelStorage(configId: string, value: ModelStorageInput) { + return request( + `/model-services/${configId}/storage`, + json("POST", value), + ); +} + export function discoverModels(value: ModelConfigInput, configId?: string) { return request<{ models: string[] }>( "/model-configs/discover", diff --git a/src/backend/rules.ts b/src/backend/rules.ts index 3d829341a..8ebc91c90 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"; @@ -60,6 +61,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"]; @@ -157,11 +161,34 @@ 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 seedAudio = config.inputRules.profile === "seed-audio"; + const unusable = + (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: "tts", + audioMode: unified ? "unified" : "tts", + audioTask: tasks.length ? task : undefined, + ...(dubbing || task === "separation" + ? { outputVideo: undefined } + : {}), + ...(dubbing + ? {} + : { + targetLanguage: undefined, + 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 } @@ -235,7 +262,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 ( @@ -630,6 +657,13 @@ export function backendBlocker( return tNow("errors.rules.bodyModel"); 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") @@ -718,7 +752,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/CanvasNodeView.tsx b/src/canvas/CanvasNodeView.tsx index adabc58b5..200fa1792 100644 --- a/src/canvas/CanvasNodeView.tsx +++ b/src/canvas/CanvasNodeView.tsx @@ -213,7 +213,33 @@ function CanvasNodeContents({ id, data, selected }: NodeProps) { } /> )} - {kind === "audio" && ( + {kind === "audio" && data.mimeType?.startsWith("video/") && ( + + 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({