diff --git a/docs/guides/cli.md b/docs/guides/cli.md index b5c29b91f..beb80eb52 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -143,6 +143,17 @@ opendirector --project PROJECT_UUID canvas add-material --asset ASSET_UUID --x 0 `asset import-url` enables only yt-dlp's site extractors (not the generic extractor), selects only formats downloaded directly over HTTP(S) (videos offered only as HLS/DASH segment streams or as sections return `url_import_unsupported`); inside the download process yt-dlp may start only ffmpeg/ffprobe on local files and deno without network permission, while external downloaders, PhantomJS and other programs are refused, so every network request passes the address check below, refuses playlists and live streams, and limits videos to 15 minutes and 512 MB; when the size is unknown it is counted during the download, which stops once the limit is exceeded. The download runs in a separate process that connects directly, without the system proxy. Every name that process resolves, including redirects and media servers, must resolve only to public addresses; loopback, private, link-local, reserved (including NAT64), multicast and other non-public answers refuse the connection with `url_import_private`. Cancellation, the timeout or the end of the calling process (including a stopped Agent turn) ends the download process and anything it started; on Windows, when the caller itself is killed, the download process exits but an ffmpeg it started may run to completion. The CLI downloads on its own machine and then registers through the same path as `asset import`, so the edit lease is held only for registration, not for the download. The receipt includes `assetId` and the source page (`url`, `title`, `site`, `durationSeconds`). In an Agent turn the file is kept under `downloads/` in the execution directory and reported as `file`; otherwise a temporary directory is used unless `--output-dir` is given. Repeating the same `--operation-id` with the same link returns the original receipt (`replayed: true`) without downloading again; the same `--operation-id` with a different link returns `url_import_operation_conflict`. In an Agent turn the downloaded file in the execution directory is reused. Which sites work depends on yt-dlp's site extractors: some sites block server and data-centre addresses, and sites such as YouTube can additionally need yt-dlp's JavaScript runtime components, which this feature does not install. Such failures return `url_import_failed` with the reason; download the file manually and register it with `asset import`. The canvas **Import video from link** action downloads on the server into an upload handle (one link per handle; another link returns `url_import_handle_conflict`) and then runs the same `asset.import`. Closing the dialog or disconnecting ends the download process and registers nothing. +## Create a speech node / 创建语音节点 + +```sh +opendirector --project PROJECT_UUID --operation-id OPERATION_UUID audio create-speech \ + --model MODEL_CONFIG_UUID --text "一段旁白,两种配乐。" --voice Vivian --x 120 --y 80 +``` + +Choose a configured TTS model. Use a provider voice ID or save one object from the `voices` array returned by `opendirector voice list --model MODEL_CONFIG_UUID` and pass it with `--voice-selection FILE`. Generation rechecks the voice against the provider on submission. Models that support a default voice also accept a call without either option. The receipt contains the editable canvas item and generation spec IDs. Run its `next.command` to submit those revisions. For a retry, reuse the operation ID, the original model selector (UUID or exact name), the other arguments and the contents of any voice record. + +选择已配置的 TTS 模型。音色可用服务端 ID,也可将 `opendirector voice list --model MODEL_CONFIG_UUID` 返回的 `voices` 数组中的一个对象保存为文件,并以 `--voice-selection FILE` 指定;提交时会向服务端复核音色。支持默认音色的模型可省略音色选项。创建回执包含可编辑节点和生成配置的 ID;执行其中的 `next.command` 才会提交这两个版本。重试时请沿用原操作 ID、原来填写的模型 UUID 或完整名称及其他参数。使用音色文件时也要保留原记录。 + ## Voice library `opendirector voice list --model MODEL_CONFIG_UUID` reads the full library and returns the selected model's connection identity, voices and adapter requirements. For a large MOSS library, request up to 150 voices per page. diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 2982c1daf..3535bc816 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -37,6 +37,7 @@ ASSET_DOWNLOAD_ENGLISH, ASSET_REVISION_HEADER, AssetDownloadFile, AssetDownloadReceipt, ) from opendirector.domain.creation.commands import COMMAND_MODELS, command_fingerprint, parse_command +from opendirector.domain.creation.generation import VoiceSelection from opendirector.domain.creation.contract_messages import CONTRACT_MESSAGES, contract_message, kebab from opendirector.domain.projects import ProjectError from opendirector.domain.timeline_errors import timeline_error, timeline_error_message @@ -51,9 +52,14 @@ app = typer.Typer(no_args_is_help=True, help="Start OpenDirector and create or edit projects.", epilog="Run opendirector COMMAND --help for subcommands and usage. " "Place --project, --url and other global options before the command.") +def cli_text(english, chinese): + return chinese if os.environ.get("OPENDIRECTOR_LANGUAGE", "en-US").lower().startswith("zh") else english + + GROUP_HELP = { "project": "List, inspect, create, rename, trash or restore projects.", "model": "Inspect available model configurations and input capabilities.", + "audio": cli_text("Configure editable audio generation nodes in the project.", "配置工程中的可编辑音频生成节点。"), "voice": "List, create or delete voices on a configured speech service.", "asset": "Import or download files and manage registered project assets.", "canvas": "Display, arrange, hide and configure canvas items.", @@ -1283,19 +1289,93 @@ def video_create(ctx: typer.Context, "binding": {"role": "generation", "objectRef": {"id": spec_id}}}, "references": references, }, identity=operation) + emit_generation_plan(receipt, project_id, operation, spec_id, item_id, "Submit this configured video generation.") + + +def emit_generation_plan(receipt, project_id, operation, spec_id, item_id, description, route=()): changed = {item["objectType"]: item for item in receipt["changed"]} spec_revision = changed["generation_spec"]["revision"] item_revision = changed["canvas_item"]["revision"] - submit = ["opendirector", "--project", project_id, "--operation-id", str(uuid5(operation, "submit")), "generation", "submit", + submit = ["opendirector", *route, "--project", project_id, "--operation-id", str(uuid5(operation, "submit")), "generation", "submit", "--spec-id", spec_id, "--expected-spec-revision", str(spec_revision), "--origin-item-id", item_id, "--expected-version", f"generation_spec:{spec_id}:{spec_revision}", "--expected-version", f"canvas_item:{item_id}:{item_revision}"] emit({**receipt, "specId": spec_id, "itemId": item_id, - "next": {"description": "Submit this configured video generation.", + "next": {"description": description, "command": shlex.join(submit)}}) +@group("audio").command("create-speech", help=cli_text("Create a visible speech node and return its submit command.", + "创建可见的语音节点并返回提交命令。")) +def audio_create_speech(ctx: typer.Context, + model: Annotated[str, typer.Option(help=cli_text("TTS model configuration UUID or unique exact name.", "TTS 模型配置 UUID 或唯一的完整模型名。"))], + text: Annotated[str, typer.Option(help=cli_text("Exact words to speak.", "需要朗读的原文。"))], + x: Annotated[float, typer.Option(help=cli_text("Canvas X coordinate.", "画布 X 坐标。"))], + y: Annotated[float, typer.Option(help=cli_text("Canvas Y coordinate.", "画布 Y 坐标。"))], + voice: Annotated[str | None, typer.Option(help=cli_text("Provider voice ID or name.", "服务端音色 ID 或名称。"))] = None, + voice_selection: Annotated[Path | None, typer.Option(help=cli_text("Saved voice record from this connection.", "当前连接中保存的音色记录文件。"))] = None): + client = ctx.obj + client.command = ctx.command_path + if not text.strip(): + raise ProjectError(cli_text("Enter the text to speak.", "请输入需要朗读的文本。")) + parameters = {"creationType": "audio", "mode": "tts"} + selection = None + if voice_selection is not None: + try: + record = read_file(voice_selection) + selection = VoiceSelection.model_validate({k: v for k, v in record.items() if k in VoiceSelection.model_fields}) + except (OSError, ValueError) as error: + raise ProjectError(cli_text("Use a voice record from opendirector voice list for this connection.", + "请使用 opendirector voice list 返回的当前连接音色记录。")) from error + if not selection.voiceId.strip(): + raise ProjectError(cli_text("The saved voice record needs a voice ID.", "保存的音色记录需要包含音色 ID。")) + if voice is not None and voice != selection.voiceId: + raise ProjectError(cli_text("The voice selection must match --voice.", "音色记录必须与 --voice 一致。")) + voice = selection.voiceId + parameters["voiceSelection"] = selection.model_dump(mode="json", exclude_none=True) + if voice is not None: + if not voice.strip(): + raise ProjectError(cli_text("Enter a voice ID or omit --voice.", "请输入音色 ID 或省略 --voice。")) + parameters["voice"] = voice + context = client.call("read_project", {}) if client.live else None + snapshot = context["project"] if context is not None else client.snapshot() + project_id = snapshot["project"]["id"] + operation = client.operation_id or uuid4() + spec_id = str(uuid5(operation, f"speech:{model}")) + item_id = str(uuid5(operation, "item")) + saved = next((s for s in snapshot["generationSpecs"] if s["id"] == spec_id), None) + if saved is not None: + original = saved if saved["revision"] == 1 else client.query("object.get", objectId=spec_id, revision=1) + model_id = original["modelConfigId"] + else: + from opendirector.integrations.model_adapters import capabilities_of + + models = context["models"] if context is not None else client.models() + config = select_model([m for m in models if m["kind"] == "audio"], model) + rules = config.get("inputRules") or {} + if "audio.speech" not in capabilities_of(config): + raise ProjectError(cli_text("Select a text-to-speech model. See opendirector model list --kind audio.", + "请选择文本转语音模型。可运行 opendirector model list --kind audio 查看。")) + if selection and selection.connectionId != (rules.get("voiceLibrary") or {}).get("connectionId"): + raise ProjectError(cli_text("Choose a voice from this model connection.", "请选择此模型连接中的音色。")) + model_id = config["id"] + receipt = client.execute("canvas.createGeneration", { + "spec": {"id": spec_id, "projectId": project_id, "kind": "audio", "purpose": "generation", + "modelConfigId": model_id, "prompt": text, "parameters": parameters}, + "item": {"id": item_id, "projectId": project_id, "kind": "audio", + "position": {"x": x, "y": y}, + "binding": {"role": "generation", "objectRef": {"id": spec_id}}}, + }, identity=operation) + route = [] + if not client.live: + route.extend(["--url", str(client.http.base_url).rstrip("/")]) + if not client.owns_session: + route.extend(["--session", client.session]) + description = cli_text("Submit this configured speech generation.", "提交此语音生成配置。") + emit_generation_plan(receipt, project_id, operation, spec_id, item_id, description, route) + + @group("job").command("show", help="Read job status once. Use job wait to wait for completion.") def job_show(ctx: typer.Context, job_id: UUID): ctx.obj.command = ctx.command_path diff --git a/tests/test_cli.py b/tests/test_cli.py index aba07fb0e..8e96e9a5e 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -120,6 +120,186 @@ def test_agent_voice_create_forwards_recording_path(tmp_path, monkeypatch): client.request.assert_not_called() +@pytest.fixture +def speech_cli(tmp_path, monkeypatch): + api = TestClient(create_app(LocalProjects(tmp_path)), headers={"X-OpenDirector-Request": "1"}) + original = httpx.Client + + def forward(request): + response = api.request(request.method, request.url.path, content=request.read(), headers=dict(request.headers)) + return httpx.Response(response.status_code, content=response.content, headers=response.headers) + + monkeypatch.setattr(cli.httpx, "Client", lambda **kwargs: original(**kwargs, transport=httpx.MockTransport(forward))) + runner = CliRunner() + prefix = ["--url", "http://127.0.0.1:19487", "--session", str(uuid4()), "--project", str(uuid4())] + + def invoke(args, *, ok=True): + result = runner.invoke(cli.app, prefix + args) + if not ok: + assert result.exit_code != 0 + return result + assert result.exit_code == 0, result.output + return json.loads(result.output) + + invoke(["project", "create", "--name", "Narration"]) + configs = ModelConfigs(tmp_path) + speech = configs.save("audio", "http://127.0.0.1:9091/v1", "Qwen3-TTS", "", + connection_type="self_hosted", protocol="openai", auth_mode="none", capability_auto_check=False) + return invoke, prefix, configs, speech + + +@pytest.mark.parametrize("selector", ["id", "modelId"]) +def test_create_speech_replays_after_model_removal(speech_cli, selector): + invoke, prefix, configs, speech = speech_cli + command = ["--operation-id", str(uuid4()), "audio", "create-speech", "--model", speech[selector], + "--text", "Say this exactly.", "--voice", "Vivian", "--x", "120", "--y", "30"] + receipt = invoke(command) + snapshot = invoke(["project", "show"]) + spec, = snapshot["generationSpecs"] + item, = snapshot["canvasItems"] + assert (spec["id"], item["id"]) == (receipt["specId"], receipt["itemId"]) + assert spec["projectId"] == prefix[-1] and item["binding"]["objectRef"]["id"] == spec["id"] + assert spec["prompt"] == "Say this exactly." and spec["parameters"]["voice"] == "Vivian" + assert item["position"] == {"x": 120, "y": 30} + assert spec["modelConfigId"] == speech["id"] and not snapshot["jobs"] + submit = shlex.split(receipt["next"]["command"]) + for flag in ("--url", "--session", "--project"): + assert submit[submit.index(flag) + 1] == prefix[prefix.index(flag) + 1] + assert f"canvas_item:{item['id']}:{item['revision']}" in submit + assert f"generation_spec:{spec['id']}:{spec['revision']}" in submit + invoke(["generation-spec", "update", "--spec", json.dumps({**spec, "prompt": "A later edit."}), + "--expected-version", f"generation_spec:{spec['id']}:{spec['revision']}"]) + stale = CliRunner().invoke(cli.app, submit[1:]) + assert stale.exit_code == 1, stale.output + refusal = json.loads(stale.output) + assert refusal["status"] == "rejected" and not refusal["jobIds"] + configs.delete(speech["id"]) + assert invoke(command) == receipt + conflicting = list(command) + conflicting[conflicting.index("--text") + 1] = "Changed intent" + invoke(conflicting, ok=False) + final = invoke(["project", "show"]) + updated, = final["generationSpecs"] + assert updated["prompt"] == "A later edit." and updated["revision"] > spec["revision"] + assert not final["jobs"] + + +def test_create_speech_with_a_temporary_session(speech_cli, monkeypatch): + _, prefix, _, model = speech_cli + monkeypatch.delenv("OPENDIRECTOR_SESSION", raising=False) + project = str(uuid4()) + route = ["--url", prefix[1], "--project", project] + runner = CliRunner() + created = runner.invoke(cli.app, [*route, "project", "create", "--name", "Temporary session"]) + assert created.exit_code == 0, created.output + command = [*route, "--operation-id", str(uuid4()), "audio", "create-speech", "--model", model["id"], + "--text", "Speak.", "--x", "0", "--y", "0"] + first = runner.invoke(cli.app, command) + assert first.exit_code == 0, first.output + followup = shlex.split(json.loads(first.output)["next"]["command"]) + assert "--session" not in followup and followup[1:5] == route + retry = runner.invoke(cli.app, command) + assert retry.exit_code == 0 and json.loads(retry.output) == json.loads(first.output) + + +@pytest.mark.parametrize(("url", "model", "voice"), [ + ("https://api.mosi.cn/v1", "moss-tts-1.5-flash", "voice_1.demo-name"), + ("https://api.minimax.cn/v1", "speech-2.8-hd", "Chinese (Mandarin)_Reliable_Executive"), + ("https://open.bigmodel.cn/api/paas/v4", "glm-tts", "tongtong"), +], ids=["moss", "minimax", "glm-tts"]) +def test_create_speech_with_provider_tts(speech_cli, tmp_path, url, model, voice): + invoke, _, configs, _ = speech_cli + config = configs.save("audio", url, model, "test-key", protocol="openai", capability_auto_check=False) + selection = {"connectionId": config["inputRules"]["voiceLibrary"]["connectionId"], "voiceId": voice, + "name": "Narrator", "source": "builtin", "hasReferenceAudio": False} + voice_file = tmp_path / "voice.json" + voice_file.write_text(json.dumps(selection)) + receipt = invoke(["audio", "create-speech", "--model", config["id"], "--text", "Read this.", + "--voice-selection", str(voice_file), "--x", "10", "--y", "20"]) + state = invoke(["project", "show"]) + spec, = state["generationSpecs"] + item, = state["canvasItems"] + assert item["id"] == receipt["itemId"] and item["kind"] == "audio" + assert item["binding"]["objectRef"]["id"] == spec["id"] == receipt["specId"] + assert spec["modelConfigId"] == config["id"] and spec["prompt"] == "Read this." + assert spec["parameters"]["mode"] == "tts" and spec["parameters"]["voice"] == voice + assert spec["parameters"]["voiceSelection"]["connectionId"] == selection["connectionId"] + assert not state["jobs"] + + +def test_create_speech_validates_voice_selection(speech_cli, tmp_path, monkeypatch): + invoke, _, configs, speech = speech_cli + music = configs.save("audio", "http://127.0.0.1:9092/v1", "YuE2", "", + connection_type="self_hosted", protocol="vllm_omni_music", auth_mode="none", capability_auto_check=False) + command = ["audio", "create-speech", "--text", "Read this.", "--x", "10", "--y", "20"] + rejected = invoke(command + ["--model", music["id"]], ok=False) + assert "text-to-speech model" in str(rejected.exception) + args = command + ["--model", speech["id"]] + monkeypatch.setenv("OPENDIRECTOR_LANGUAGE", "zh-CN") + blank = invoke([*args[:3], " ", *args[4:]], ok=False) + assert "请输入" in str(blank.exception) + default = invoke(args) + spec, = invoke(["project", "show"])["generationSpecs"] + assert spec["parameters"].get("voice") is None + assert default["next"]["description"] == "提交此语音生成配置。" + record = {"connectionId": speech["inputRules"]["voiceLibrary"]["connectionId"], "voiceId": "chosen", + "name": "Chosen", "source": "builtin", "hasReferenceAudio": False} + file = tmp_path / "voice.json" + for content in (None, b"{", b"[]", b"\xff", json.dumps({**record, "voiceId": 123}).encode(), + json.dumps({**record, "voiceId": " "}).encode()): + if content is not None: + file.write_bytes(content) + invalid = invoke([*args, "--voice-selection", str(file)], ok=False) + assert "音色记录" in str(invalid.exception) + file.write_text(json.dumps({**record, "connectionId": "another"})) + invoke([*args, "--voice-selection", str(file)], ok=False) + file.write_text(json.dumps({**record, "compatible": True})) + invoke([*args, "--voice-selection", str(file), "--voice", "other"], ok=False) + from_file = ["--operation-id", str(uuid4()), *args, "--voice-selection", str(file)] + selected = invoke(from_file) + configs.delete(speech["id"]) + assert invoke(from_file) == selected + file.write_text(json.dumps({**record, "voiceId": "different"})) + refused = invoke(from_file, ok=False) + assert isinstance(refused.exception, ProjectError) + snapshot = invoke(["project", "show"]) + assert len(snapshot["canvasItems"]) == 2 and not snapshot["jobs"] + params = next(s["parameters"] for s in snapshot["generationSpecs"] if s["id"] == selected["specId"]) + assert params["voice"] == "chosen" + assert {k: params["voiceSelection"][k] for k in record} == record + + +def test_create_speech_uses_scoped_agent_gateway(monkeypatch): + project, model = str(uuid4()), str(uuid4()) + monkeypatch.setenv("OPENDIRECTOR_AGENT_SOCKET", "test-gateway") + calls = [] + + def gateway(self, name, arguments, *, identity=None): + calls.append(name) + if name == "read_project": + return {"project": {"project": {"id": project}, "generationSpecs": [], "canvasItems": []}, + "models": [{"id": model, "modelId": "TTS", "kind": "audio", "url": "http://127.0.0.1:9091/v1", + "protocol": "openai", "connectionType": "self_hosted", "inputRules": {"profile": "tts"}}]} + if name == "query": + assert arguments["type"] == "object.get" + return {"id": arguments["objectId"], "kind": "audio", "revision": 1, "parentId": None, + "position": {"x": 0, "y": 0}, "width": 352, "height": 112, "visible": True} + assert name == "execute_command" and arguments["type"] == "canvas.createGeneration" + assert arguments["payload"]["spec"]["projectId"] == project and identity is not None + return {"status": "applied", "changed": [{"objectType": "generation_spec", "revision": 1, + "id": arguments["payload"]["spec"]["id"]}, + {"objectType": "canvas_item", "revision": 1, + "id": arguments["payload"]["item"]["id"]}]} + + monkeypatch.setattr(cli.Client, "call", gateway) + result = CliRunner().invoke(cli.app, ["audio", "create-speech", "--model", model, "--text", "Hello", + "--x", "0", "--y", "0"]) + assert result.exit_code == 0, result.output + submit = shlex.split(json.loads(result.output)["next"]["command"]) + assert "--url" not in submit and "--session" not in submit + assert calls == ["read_project", "execute_command", "query"] + + def test_cli_project_write_replay_and_lock(tmp_path, monkeypatch): api = TestClient(create_app(LocalProjects(tmp_path)), headers={"X-OpenDirector-Request": "1"}) original_client = httpx.Client