@nimiplatform/app-tools 0.6.3 → 0.11.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +153 -12
- package/bin/nimi-app.mjs +16 -14
- package/lib/app-access-declaration.mjs +1 -0
- package/lib/app-dependency-combinations.mjs +49 -0
- package/lib/app-doctor-update.mjs +84 -23
- package/lib/app-info.mjs +33 -3
- package/lib/app-lifecycle-guidance.mjs +4 -2
- package/lib/app-pack.mjs +5 -2
- package/lib/app-project-lifecycle.mjs +284 -53
- package/lib/app-safety-profile.mjs +204 -0
- package/lib/app-scaffold-capabilities.mjs +11 -3
- package/lib/app-scaffold-profiles.mjs +136 -27
- package/lib/app-scaffold.mjs +55 -7
- package/lib/canonical-capability-ids.generated.mjs +25 -0
- package/lib/index.mjs +0 -4
- package/package.json +27 -31
- package/scripts/dev-shell.mjs +80 -18
- package/skills/nimi-app-lifecycle/SKILL.md +7 -3
- package/skills/nimi-app-lifecycle/references/acceptance.md +7 -1
- package/skills/nimi-app-lifecycle/references/adapt.md +46 -1
- package/skills/nimi-app-lifecycle/references/audit.md +55 -0
- package/skills/nimi-app-lifecycle/references/platform-gaps.md +15 -0
- package/skills/nimi-app-lifecycle/references/release.md +2 -2
- package/skills/nimi-app-lifecycle/references/safety-declaration.md +37 -0
- package/skills/nimi-app-lifecycle/references/upgrade-platform.md +16 -2
- package/templates/app-source/src/ai-studio-core/ai-config.ts +17 -3
- package/templates/app-source/src/ai-studio-core/ai-studio-core.css +40 -3
- package/templates/app-source/src/ai-studio-core/audio-separation-request.ts +24 -0
- package/templates/app-source/src/ai-studio-core/contexts.tsx +4 -0
- package/templates/app-source/src/ai-studio-core/history-policy.ts +395 -41
- package/templates/app-source/src/ai-studio-core/history.ts +262 -10
- package/templates/app-source/src/ai-studio-core/host-context.tsx +15 -2
- package/templates/app-source/src/ai-studio-core/index.ts +15 -4
- package/templates/app-source/src/ai-studio-core/job-recovery-panel.tsx +105 -0
- package/templates/app-source/src/ai-studio-core/job-recovery.ts +224 -0
- package/templates/app-source/src/ai-studio-core/managed-result-references.ts +79 -0
- package/templates/app-source/src/ai-studio-core/messages/en.json +185 -10
- package/templates/app-source/src/ai-studio-core/messages/zh.json +185 -10
- package/templates/app-source/src/ai-studio-core/module-registration.ts +9 -1
- package/templates/app-source/src/ai-studio-core/non-success-presentation.ts +81 -2
- package/templates/app-source/src/ai-studio-core/parameters.ts +34 -1
- package/templates/app-source/src/ai-studio-core/runtime-types.ts +124 -8
- package/templates/app-source/src/ai-studio-core/runtime.ts +218 -20
- package/templates/app-source/src/ai-studio-core/section-ai-testing-annotation-result.tsx +123 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-artifact-preview.ts +3 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-audio-separation-result.tsx +26 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-composer.tsx +14 -7
- package/templates/app-source/src/ai-studio-core/section-ai-testing-decision-result.tsx +76 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-exchange-result.tsx +71 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-history.tsx +20 -4
- package/templates/app-source/src/ai-studio-core/section-ai-testing-input.ts +29 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-music-result.tsx +45 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-output.tsx +132 -10
- package/templates/app-source/src/ai-studio-core/section-ai-testing-result.tsx +122 -38
- package/templates/app-source/src/ai-studio-core/section-ai-testing-run.ts +4 -3
- package/templates/app-source/src/ai-studio-core/section-ai-testing-session-result.tsx +66 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-studio-result.tsx +100 -22
- package/templates/app-source/src/ai-studio-core/section-ai-testing-surface.tsx +6 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-transcript-result.tsx +45 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-transcription-result.tsx +106 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-vision-result.tsx +23 -4
- package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-asset-actions.tsx +40 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing-voice-conversion-result.tsx +20 -0
- package/templates/app-source/src/ai-studio-core/section-ai-testing.tsx +219 -35
- package/templates/app-source/src/ai-studio-core/text-annotation-document.ts +50 -0
- package/templates/app-source/src/ai-studio-core/text-media-replay.ts +51 -0
- package/templates/app-source/src/ai-studio-core/voice-assets.ts +17 -0
- package/templates/app-source/src/ai-studio-core/workspace.tsx +48 -6
- package/templates/app-source/src/studio-modules/studio-create/descriptors.ts +1 -1
- package/templates/app-source/src/studio-modules/studio-create/messages/en.json +13 -1
- package/templates/app-source/src/studio-modules/studio-create/messages/zh.json +13 -1
- package/templates/app-source/src/studio-modules/studio-create/parameter-panel.tsx +11 -2
- package/templates/app-source/src/studio-modules/studio-create/parameters.ts +2 -2
- package/templates/app-source/src/studio-modules/studio-create/registration.ts +2 -2
- package/templates/app-source/src/studio-modules/studio-create/runtime.ts +121 -3
- package/templates/app-source/src/studio-modules/studio-media/audio-separate-parameters.tsx +72 -0
- package/templates/app-source/src/studio-modules/studio-media/audio-separate-runtime.ts +90 -0
- package/templates/app-source/src/studio-modules/studio-media/descriptors.ts +16 -1
- package/templates/app-source/src/studio-modules/studio-media/index.ts +2 -0
- package/templates/app-source/src/studio-modules/studio-media/messages/en.json +225 -7
- package/templates/app-source/src/studio-modules/studio-media/messages/zh.json +225 -7
- package/templates/app-source/src/studio-modules/studio-media/music-parameters.tsx +85 -0
- package/templates/app-source/src/studio-modules/studio-media/music-transcription-parameters.tsx +85 -0
- package/templates/app-source/src/studio-modules/studio-media/music-transcription-runtime.ts +64 -0
- package/templates/app-source/src/studio-modules/studio-media/parameter-panel.tsx +9 -26
- package/templates/app-source/src/studio-modules/studio-media/parameters.ts +170 -6
- package/templates/app-source/src/studio-modules/studio-media/registration.ts +29 -1
- package/templates/app-source/src/studio-modules/studio-media/runtime.ts +90 -6
- package/templates/app-source/src/studio-modules/studio-media/vision-parameters.tsx +1 -0
- package/templates/app-source/src/studio-modules/studio-media/vision-runtime.ts +23 -5
- package/templates/app-source/src/studio-modules/studio-media/voice-convert-parameters.tsx +132 -0
- package/templates/app-source/src/studio-modules/studio-media/voice-convert-runtime.ts +120 -0
- package/templates/app-source/src/studio-modules/studio-voice/audio-url.ts +25 -0
- package/templates/app-source/src/studio-modules/studio-voice/messages/en.json +4 -4
- package/templates/app-source/src/studio-modules/studio-voice/messages/zh.json +4 -4
- package/templates/app-source/src/studio-modules/studio-voice/parameters.ts +36 -10
- package/templates/app-source/src/studio-modules/studio-voice/runtime.ts +66 -30
- package/templates/app-source/src/workbench-core/index.ts +2 -0
- package/templates/app-source/src/workbench-core/runtime-gate.tsx +102 -6
- package/templates/app-source/src/workbench-core/workbench-core.css +42 -0
- package/templates/app-source/src/workbench-core/workbench-core.tsx +69 -18
- package/templates/app-source.manifest.json +100 -0
- package/templates/default-starter/AGENTS.md +4 -2
- package/templates/default-starter/README.md +2 -1
- package/templates/default-starter/src/shell/workbench-target-adapter.ts +102 -12
- package/templates/default-starter.manifest.json +0 -4
- package/lib/simulator-conformance-ast.mjs +0 -498
- package/lib/simulator-conformance-css.mjs +0 -116
- package/lib/simulator-conformance-graph.mjs +0 -757
- package/lib/simulator-conformance.d.mts +0 -14
- package/lib/simulator-conformance.mjs +0 -203
- package/lib/simulator-css-profile.d.mts +0 -27
- package/lib/simulator-css-profile.mjs +0 -531
- package/lib/simulator-kit-export-resolution.mjs +0 -70
- package/lib/simulator-manifest.mjs +0 -334
|
@@ -1,7 +1,13 @@
|
|
|
1
|
+
import { observeRuntimeImageGenerate, observeRuntimeVideoGenerate } from '@nimiplatform/kit/features/generation/runtime';
|
|
2
|
+
import { ScenarioType } from '@nimiplatform/sdk/runtime/generated';
|
|
3
|
+
import { beginStudioJobRecovery, recordedStudioScenarioJobClient, recoverStudioJobId, readStudioJobRecovery, restoreSavedStudioJobResult, saveStudioJobRecoveryResult, studioJobRecoverySignal } from '../../ai-studio-core/job-recovery.js';
|
|
1
4
|
import type { StudioCapabilityRuntimeHandlers } from '../../ai-studio-core/runtime-dispatcher.js';
|
|
2
5
|
import { runVisionLocate } from './vision-runtime.js';
|
|
6
|
+
import { runMusicTranscribe } from './music-transcription-runtime.js';
|
|
7
|
+
import { runVoiceConvert } from './voice-convert-runtime.js';
|
|
8
|
+
import { runAudioSeparate } from './audio-separate-runtime.js';
|
|
3
9
|
import {
|
|
4
|
-
createStudioScenarioJobClient,
|
|
10
|
+
createStudioScenarioJobClient, recoverStudioJobAction,
|
|
5
11
|
projectStudioArtifactRunnerResult,
|
|
6
12
|
type StudioCapabilityRuntimeContext,
|
|
7
13
|
} from '../../ai-studio-core/runtime.js';
|
|
@@ -18,11 +24,25 @@ export const studioMediaRuntimeHandlers: StudioCapabilityRuntimeHandlers = Objec
|
|
|
18
24
|
'image.generate': runImageGenerate,
|
|
19
25
|
'video.generate': runVideoGenerate,
|
|
20
26
|
'music.generate': runMusicGenerate,
|
|
27
|
+
'music.transcribe': runMusicTranscribe,
|
|
28
|
+
'audio.voice.convert': runVoiceConvert,
|
|
29
|
+
'audio.separate': runAudioSeparate,
|
|
21
30
|
});
|
|
22
31
|
|
|
23
32
|
async function runImageGenerate(context: StudioCapabilityRuntimeContext) {
|
|
33
|
+
const recovery = await recoverStudioJobAction(context, ScenarioType.IMAGE_GENERATE);
|
|
34
|
+
if (recovery) {
|
|
35
|
+
if (recovery.saved) return recovery.saved;
|
|
36
|
+
const result = await observeRuntimeImageGenerate({ runtime: { ai: createStudioScenarioJobClient(context) }, jobId: recovery.jobId!,
|
|
37
|
+
signal: context.input.observationSignal, cancelSignal: context.input.signal, abortReason: context.host.abortReason,
|
|
38
|
+
onJobUpdate: context.input.onJobUpdate, onObservation: context.input.onObservation });
|
|
39
|
+
return projectStudioArtifactRunnerResult(context, result);
|
|
40
|
+
}
|
|
24
41
|
if (!context.prompt) return inputRequired(context);
|
|
25
42
|
const parameters = context.input.parameters as StudioImageGenerationParameters | undefined;
|
|
43
|
+
if (parameters?.referenceImage?.trim() && parameters.referenceImageArtifactId?.trim()) {
|
|
44
|
+
return context.host.nonSuccess(context.capability, 'input-invalid', context.host.translate('Studio.parameters.imageReferenceExclusive'));
|
|
45
|
+
}
|
|
26
46
|
const result = await context.host.runners.imageGenerate({
|
|
27
47
|
runtime: { ai: createStudioScenarioJobClient(context) },
|
|
28
48
|
appId: context.host.appId,
|
|
@@ -39,6 +59,8 @@ async function runImageGenerate(context: StudioCapabilityRuntimeContext) {
|
|
|
39
59
|
...(parameters?.mask !== undefined ? { mask: parameters.mask } : {}),
|
|
40
60
|
scenarioId: context.scenarioId,
|
|
41
61
|
surfaceId: context.host.surfaceId,
|
|
62
|
+
observationSignal: context.input.observationSignal,
|
|
63
|
+
onObservation: context.input.onObservation,
|
|
42
64
|
...(context.input.signal ? {
|
|
43
65
|
signal: context.input.signal,
|
|
44
66
|
abortReason: context.host.abortReason,
|
|
@@ -49,36 +71,98 @@ async function runImageGenerate(context: StudioCapabilityRuntimeContext) {
|
|
|
49
71
|
|
|
50
72
|
async function runMusicGenerate(context: StudioCapabilityRuntimeContext) {
|
|
51
73
|
const parameters = context.input.parameters as StudioMusicGenerationParameters | undefined;
|
|
52
|
-
|
|
53
|
-
|
|
74
|
+
if (parameters?.recoverySubmissionId) {
|
|
75
|
+
const entry = (await readStudioJobRecovery(context.host.client.storage)).find((item) => item.clientSubmissionId === parameters.recoverySubmissionId);
|
|
76
|
+
if (!entry) throw new Error(context.host.translate('Music.recoveryMissing'));
|
|
77
|
+
const saved = await restoreSavedStudioJobResult(entry, context.capability.label, 'music.generate', context.host.client.storage.assets, studioJobRecoverySignal(context.input));
|
|
78
|
+
if (saved) return saved;
|
|
79
|
+
const recoveredJobId = await recoverStudioJobId(context.host.client, entry, 'music.generate');
|
|
80
|
+
const result = await context.host.runners.musicObserve({ runtime: { ai: createStudioScenarioJobClient(context) },
|
|
81
|
+
jobId: recoveredJobId, signal: context.input.observationSignal, cancelSignal: context.input.signal, onObservation: context.input.onObservation, abortReason: context.host.abortReason, onJobUpdate: context.input.onJobUpdate });
|
|
82
|
+
const projected = await projectStudioArtifactRunnerResult(context, result);
|
|
83
|
+
await saveStudioJobRecoveryResult(context.host.client.storage, entry.clientSubmissionId, projected);
|
|
84
|
+
return projected;
|
|
85
|
+
}
|
|
86
|
+
const lyrics = parameters?.lyrics ?? '';
|
|
87
|
+
if (!context.prompt) return inputRequired(context);
|
|
88
|
+
const snapshot = await context.host.client.aiConfig.get();
|
|
89
|
+
const selected = snapshot.effectiveSelections.find((item) => item.capabilityContract === 'music.generate');
|
|
90
|
+
const resource = selected?.resource;
|
|
91
|
+
const capabilities = resource?.oneofKind === 'local' ? resource.local.musicInput : resource?.oneofKind === 'cloud' ? resource.cloud.target?.musicInput : undefined;
|
|
92
|
+
const profile = capabilities?.generation.find((item) => item.scoreMode === (parameters?.scoreRelativePath ? 'required' : 'unsupported'));
|
|
93
|
+
if (selected?.state !== 'ready' || !profile) return context.host.nonSuccess(context.capability, 'input-invalid', context.host.translate('Music.configureInputs'));
|
|
94
|
+
let score: { artifactId: string; format: 'abc' } | undefined;
|
|
95
|
+
if (parameters?.scoreRelativePath) {
|
|
96
|
+
const input = await context.host.client.storage.assets.read({ relativePath: parameters.scoreRelativePath });
|
|
97
|
+
if (input.asset.mediaType !== 'text/vnd.abc' || input.asset.sizeBytes < 1 || input.asset.sizeBytes > profile.maxScoreBytes) throw new Error(context.host.translate('Music.scoreTooLarge'));
|
|
98
|
+
const bytes = new Uint8Array(input.asset.sizeBytes);
|
|
99
|
+
let offset = 0;
|
|
100
|
+
for await (const chunk of input.body) {
|
|
101
|
+
if (offset + chunk.byteLength > bytes.length) throw new Error(context.host.translate('Music.scoreTooLarge'));
|
|
102
|
+
bytes.set(chunk, offset); offset += chunk.byteLength;
|
|
103
|
+
}
|
|
104
|
+
if (offset !== bytes.length) throw new Error(context.host.translate('Music.scoreIncomplete'));
|
|
105
|
+
const uploaded = await context.host.client.ai.artifacts.upload({ bytes, mimeType: 'text/vnd.abc' });
|
|
106
|
+
score = { artifactId: uploaded.artifactId, format: 'abc' };
|
|
107
|
+
}
|
|
108
|
+
// Record the author action before Submit, so a lost response remains recoverable.
|
|
109
|
+
const clientSubmissionId = await beginStudioJobRecovery(context.host.client.storage, 'music.generate', undefined, undefined,
|
|
110
|
+
undefined, context.input.recordedRunConfig, context.input.prompt);
|
|
111
|
+
const musicClient = recordedStudioScenarioJobClient(context, clientSubmissionId, 'music.generate');
|
|
54
112
|
const result = await context.host.runners.musicGenerate({
|
|
55
|
-
runtime: { ai:
|
|
113
|
+
runtime: { ai: musicClient },
|
|
56
114
|
appId: context.host.appId,
|
|
57
115
|
prompt: context.prompt,
|
|
58
116
|
lyrics,
|
|
117
|
+
...(parameters?.durationSeconds !== undefined ? { durationSeconds: parameters.durationSeconds } : {}),
|
|
118
|
+
...(parameters?.seed !== undefined ? { seed: parameters.seed } : {}),
|
|
119
|
+
...(parameters?.instrumental !== undefined ? { instrumental: parameters.instrumental } : {}),
|
|
120
|
+
...(parameters?.returnGeneratedScore !== undefined ? { returnGeneratedScore: parameters.returnGeneratedScore } : {}),
|
|
121
|
+
...(score ? { score, scoreConditioning: parameters?.scoreConditioning ?? 'melody-and-harmony' } : {}),
|
|
122
|
+
onJobUpdate: context.input.onJobUpdate,
|
|
59
123
|
scenarioId: context.scenarioId,
|
|
60
124
|
surfaceId: context.host.surfaceId,
|
|
61
|
-
|
|
125
|
+
observationSignal: context.input.observationSignal,
|
|
126
|
+
onObservation: context.input.onObservation,
|
|
127
|
+
...(context.input.signal ? { signal: context.input.signal, observationSignal: context.input.observationSignal, onObservation: context.input.onObservation, abortReason: context.host.abortReason } : {}),
|
|
62
128
|
});
|
|
63
|
-
|
|
129
|
+
const projected = await projectStudioArtifactRunnerResult(context, result);
|
|
130
|
+
await saveStudioJobRecoveryResult(context.host.client.storage, clientSubmissionId, projected);
|
|
131
|
+
return projected;
|
|
64
132
|
}
|
|
65
133
|
|
|
66
134
|
async function runVideoGenerate(context: StudioCapabilityRuntimeContext) {
|
|
135
|
+
const recovery = await recoverStudioJobAction(context, ScenarioType.VIDEO_GENERATE);
|
|
136
|
+
if (recovery) {
|
|
137
|
+
if (recovery.saved) return recovery.saved;
|
|
138
|
+
const result = await observeRuntimeVideoGenerate({ runtime: { ai: createStudioScenarioJobClient(context) }, jobId: recovery.jobId!,
|
|
139
|
+
signal: context.input.observationSignal, cancelSignal: context.input.signal, abortReason: context.host.abortReason,
|
|
140
|
+
onJobUpdate: context.input.onJobUpdate, onObservation: context.input.onObservation });
|
|
141
|
+
return projectStudioArtifactRunnerResult(context, result);
|
|
142
|
+
}
|
|
67
143
|
if (!context.prompt) return inputRequired(context);
|
|
68
144
|
const parameters = context.input.parameters as StudioVideoGenerationParameters | undefined;
|
|
69
145
|
const mode = parameters?.mode ?? 't2v';
|
|
146
|
+
if (mode === 'i2v-first-frame' && !parameters?.firstFrameImageUrl?.trim()) {
|
|
147
|
+
return context.host.nonSuccess(context.capability, 'input-invalid', context.host.translate('Studio.parameters.videoFirstFrameRequired'));
|
|
148
|
+
}
|
|
70
149
|
const result = await context.host.runners.videoGenerate({
|
|
71
150
|
runtime: { ai: createStudioScenarioJobClient(context) },
|
|
72
151
|
appId: context.host.appId,
|
|
73
152
|
mode,
|
|
74
153
|
prompt: context.prompt,
|
|
75
154
|
...(parameters?.negativePrompt !== undefined ? { negativePrompt: parameters.negativePrompt } : {}),
|
|
155
|
+
...(mode === 'i2v-first-frame' && parameters?.firstFrameImageUrl ? {
|
|
156
|
+
content: [{ type: 'image-url', role: 'first-frame', url: parameters.firstFrameImageUrl }],
|
|
157
|
+
} : {}),
|
|
76
158
|
...(mode === 'i2v-reference' && parameters?.referenceArtifactId ? {
|
|
77
159
|
content: [{ type: 'artifact-ref', role: 'reference-image', artifactId: parameters.referenceArtifactId }],
|
|
78
160
|
} : {}),
|
|
79
161
|
options: videoGenerationOptions(parameters),
|
|
80
162
|
scenarioId: context.scenarioId,
|
|
81
163
|
surfaceId: context.host.surfaceId,
|
|
164
|
+
observationSignal: context.input.observationSignal,
|
|
165
|
+
onObservation: context.input.onObservation,
|
|
82
166
|
...(context.input.signal ? {
|
|
83
167
|
signal: context.input.signal,
|
|
84
168
|
abortReason: context.host.abortReason,
|
|
@@ -4,6 +4,7 @@ import { StudioParameterField, type StudioParameterPanelProps } from '../../ai-s
|
|
|
4
4
|
import { useAIStudioHost } from '../../ai-studio-core/host-context.js';
|
|
5
5
|
|
|
6
6
|
export const studioVisionLocateParameters = defineStudioParameters<{ geometry: 'box' | 'point' }>({
|
|
7
|
+
restoreRecordedParameters: (snapshot) => snapshot?.geometry === 'box' || snapshot?.geometry === 'point' ? { geometry: snapshot.geometry } : null,
|
|
7
8
|
initial: () => ({ geometry: 'box' }), routeMatrix: { geometry: LOCAL_ONLY_STUDIO_PARAMETER },
|
|
8
9
|
});
|
|
9
10
|
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { StudioManagedArtifact } from '../../ai-studio-core/runtime-types.js';
|
|
2
|
+
import { runNimiRuntimeScenarioJob, observeNimiRuntimeScenarioJob, type NimiRuntimeScenarioJobResult } from '@nimiplatform/sdk/runtime';
|
|
2
3
|
import { ExecutionMode, ScenarioType, VisionLocateGeometry, type VisionLocateResult } from '@nimiplatform/sdk/runtime/generated';
|
|
3
4
|
import type { NimiLocalAppVisionLocateResult } from '@nimiplatform/sdk/app';
|
|
4
|
-
import { createStudioScenarioJobClient, type StudioCapabilityRuntimeContext } from '../../ai-studio-core/runtime.js';
|
|
5
|
+
import { createStudioScenarioJobClient, recoverStudioJobAction, adoptStudioJobArtifact, managedStudioAssetPath, type StudioCapabilityRuntimeContext } from '../../ai-studio-core/runtime.js';
|
|
5
6
|
|
|
6
7
|
function localVisionResult(result: VisionLocateResult): NimiLocalAppVisionLocateResult {
|
|
7
8
|
return { imageArtifactId: result.imageArtifactId, width: result.width, height: result.height,
|
|
@@ -17,6 +18,16 @@ function localVisionResult(result: VisionLocateResult): NimiLocalAppVisionLocate
|
|
|
17
18
|
|
|
18
19
|
// @nimi-authority: rule.nimi.sdks.feature-clients.r102
|
|
19
20
|
export async function runVisionLocate(context: StudioCapabilityRuntimeContext) {
|
|
21
|
+
const recovery = await recoverStudioJobAction(context, ScenarioType.VISION_LOCATE);
|
|
22
|
+
if (recovery) {
|
|
23
|
+
if (recovery.saved) return recovery.saved;
|
|
24
|
+
const details = recovery.entry.details;
|
|
25
|
+
if (!details?.sourceImage || !details.expectedVision) throw new Error('Saved Locate action is incomplete');
|
|
26
|
+
const result = await observeNimiRuntimeScenarioJob({ ai: createStudioScenarioJobClient(context), jobId: recovery.jobId!, scenarioType: ScenarioType.VISION_LOCATE,
|
|
27
|
+
expectedVision: details.expectedVision, signal: context.input.observationSignal, cancelSignal: context.input.signal,
|
|
28
|
+
abortReason: context.host.abortReason, onObservation: context.input.onObservation, onJobUpdate: context.input.onJobUpdate });
|
|
29
|
+
return projectLocateResult(context, result, details.sourceImage);
|
|
30
|
+
}
|
|
20
31
|
const t = context.host.translate;
|
|
21
32
|
const abortedBeforeSubmit = () => context.host.nonSuccess(context.capability, 'operation-aborted', t('VisionLocate.stoppedBeforeSubmit'));
|
|
22
33
|
const images = context.input.attachments ?? [];
|
|
@@ -38,21 +49,28 @@ export async function runVisionLocate(context: StudioCapabilityRuntimeContext) {
|
|
|
38
49
|
throw error;
|
|
39
50
|
}
|
|
40
51
|
if (context.input.signal?.aborted) return abortedBeforeSubmit();
|
|
52
|
+
const { asset } = await adoptStudioJobArtifact(context, upload, await managedStudioAssetPath('vision.locate.source', upload.artifactId, 0));
|
|
53
|
+
const sourceImage: StudioManagedArtifact = { ...asset, displayName: image.name, previewSource: 'managed-asset' };
|
|
41
54
|
const result = await runNimiRuntimeScenarioJob({
|
|
42
|
-
ai: createStudioScenarioJobClient(context),
|
|
55
|
+
ai: createStudioScenarioJobClient(context, { sourceImage }),
|
|
43
56
|
request: {
|
|
44
57
|
head: { appId: context.host.appId, subjectUserId: '', timeoutMs: 0 }, scenarioType: ScenarioType.VISION_LOCATE, executionMode: ExecutionMode.ASYNC_JOB,
|
|
45
58
|
spec: { spec: { oneofKind: 'visionLocate', visionLocate: { imageArtifactId: upload.artifactId, query: context.prompt, geometry: context.input.parameters?.geometry === 'point' ? VisionLocateGeometry.POINT : VisionLocateGeometry.BOX } } },
|
|
46
59
|
requestId: '', idempotencyKey: '', labels: {}, extensions: [],
|
|
47
60
|
},
|
|
48
|
-
signal: context.input.signal, abortReason: context.host.abortReason, onJobUpdate: context.input.onJobUpdate,
|
|
61
|
+
signal: context.input.signal, observationSignal: context.input.observationSignal, onObservation: context.input.onObservation, abortReason: context.host.abortReason, onJobUpdate: context.input.onJobUpdate,
|
|
49
62
|
});
|
|
63
|
+
return projectLocateResult(context, result, sourceImage, image.dataUrl);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function projectLocateResult(context: StudioCapabilityRuntimeContext, result: NimiRuntimeScenarioJobResult, sourceImage: StudioManagedArtifact, imagePreviewUrl?: string) {
|
|
67
|
+
const t = context.host.translate;
|
|
50
68
|
if (!result.visionLocate) throw new Error(t('VisionLocate.resultMissing'));
|
|
51
69
|
const locate = localVisionResult(result.visionLocate);
|
|
52
70
|
return {
|
|
53
71
|
ok: true as const, capabilityId: context.capability.id, capabilityLabel: context.capability.label,
|
|
54
72
|
message: t(locate.locations.length ? 'VisionLocate.found' : 'VisionLocate.noMatch', { count: locate.locations.length }),
|
|
55
|
-
output: { kind: 'vision-locate' as const, jobId: result.job.jobId, result: locate, imagePreviewUrl:
|
|
73
|
+
output: { kind: 'vision-locate' as const, jobId: result.job.jobId, result: locate, sourceImage, ...(imagePreviewUrl ? { imagePreviewUrl } : {}) },
|
|
56
74
|
trace: { traceId: result.traceId },
|
|
57
75
|
};
|
|
58
76
|
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { useEffect, useRef, useState } from 'react';
|
|
2
|
+
import { Button, SelectField } from '@nimiplatform/kit/ui';
|
|
3
|
+
import type { NimiVoiceConvertInputProfile } from '@nimiplatform/sdk/ai';
|
|
4
|
+
import { useAIStudioHost } from '../../ai-studio-core/host-context.js';
|
|
5
|
+
import { StudioNumberParameter, StudioParameterField, StudioTextParameter, type StudioParameterPanelProps } from '../../ai-studio-core/parameter-fields.js';
|
|
6
|
+
import type { StudioVoiceConvertParameters } from './parameters.js';
|
|
7
|
+
|
|
8
|
+
type VoiceTargetKind = NonNullable<StudioVoiceConvertParameters['targetKind']>;
|
|
9
|
+
|
|
10
|
+
export function VoiceConvertFields(props: StudioParameterPanelProps) {
|
|
11
|
+
const host = useAIStudioHost(); const { translate: t } = host;
|
|
12
|
+
const parameters = props.parameters as StudioVoiceConvertParameters;
|
|
13
|
+
const update = props.onChange as (next: StudioVoiceConvertParameters) => void;
|
|
14
|
+
const [profiles, setProfiles] = useState<readonly NimiVoiceConvertInputProfile[]>([]);
|
|
15
|
+
const [voices, setVoices] = useState<readonly { voiceAssetId: string; creationSource: string; status: string }[]>([]);
|
|
16
|
+
const [busy, setBusy] = useState<'source' | 'target' | null>(null);
|
|
17
|
+
const [error, setError] = useState('');
|
|
18
|
+
const sourceInput = useRef<HTMLInputElement>(null);
|
|
19
|
+
const targetInput = useRef<HTMLInputElement>(null);
|
|
20
|
+
useEffect(() => {
|
|
21
|
+
let active = true;
|
|
22
|
+
// Closing the drawer and a commit can both refresh; only the newest read
|
|
23
|
+
// applies, so a slower, older snapshot never undoes a newer one.
|
|
24
|
+
let requestGeneration = 0;
|
|
25
|
+
const refresh = () => {
|
|
26
|
+
const generation = ++requestGeneration;
|
|
27
|
+
void host.sdk.aiConfig.getSnapshot().then(snapshot => {
|
|
28
|
+
if (!active || generation !== requestGeneration) return;
|
|
29
|
+
const selected = snapshot.effectiveSelections.find(item => item.capabilityContract === 'audio.voice.convert');
|
|
30
|
+
setProfiles(selected?.state === 'ready' && selected.resource?.oneofKind === 'local' ? selected.resource.local.musicInput?.voiceConvert ?? [] : []);
|
|
31
|
+
setError('');
|
|
32
|
+
}).catch((cause: unknown) => { if (active && generation === requestGeneration) { setProfiles([]); setError(String(cause)); } });
|
|
33
|
+
};
|
|
34
|
+
refresh(); const unsubscribe = host.app.events.subscribeAIConfigRefresh(refresh);
|
|
35
|
+
void host.sdk.listLocalAppVoiceAssets().then(assets => { if (active) setVoices(assets); }).catch(() => { if (active) setVoices([]); });
|
|
36
|
+
return () => { active = false; unsubscribe(); };
|
|
37
|
+
}, [host]);
|
|
38
|
+
const targetKind: VoiceTargetKind = parameters.targetKind ?? 'reference-audio';
|
|
39
|
+
const profile = profiles.find(item => item.targetKinds.includes(targetKind)) ?? profiles[0];
|
|
40
|
+
const disabled = props.disabled || busy !== null;
|
|
41
|
+
async function importAudio(file: File, kind: 'source' | 'target') {
|
|
42
|
+
const extension = file.name.match(/\.(mp3|wav|flac)$/iu)?.[1]?.toLowerCase();
|
|
43
|
+
const limit = kind === 'source' ? profile?.maxSourceBytes : profile?.maxTargetBytes;
|
|
44
|
+
if (!extension || !profile || !limit || file.size < 1 || file.size > limit) { setError(t('VoiceConvert.fileInvalid')); return; }
|
|
45
|
+
const mimeType = extension === 'mp3' ? 'audio/mpeg' : extension === 'flac' ? 'audio/flac' : 'audio/wav';
|
|
46
|
+
// Do not leave the previous import executable while its replacement is
|
|
47
|
+
// still being copied. The composer requires committed input assets.
|
|
48
|
+
const remaining = { ...parameters };
|
|
49
|
+
delete remaining.recoverySubmissionId;
|
|
50
|
+
for (const field of kind === 'source'
|
|
51
|
+
? ['sourceRelativePath', 'sourceName', 'sourceMimeType', 'sourceStartSeconds', 'sourceEndSeconds'] as const
|
|
52
|
+
: ['targetRelativePath', 'targetName', 'targetMimeType', 'targetStartSeconds', 'targetEndSeconds'] as const) {
|
|
53
|
+
delete remaining[field];
|
|
54
|
+
}
|
|
55
|
+
update(remaining);
|
|
56
|
+
setBusy(kind); setError('');
|
|
57
|
+
try {
|
|
58
|
+
async function* chunks() {
|
|
59
|
+
const reader = file.stream().getReader();
|
|
60
|
+
try { while (true) { const next = await reader.read(); if (next.done) break; yield next.value; } }
|
|
61
|
+
finally { await reader.cancel(); reader.releaseLock(); }
|
|
62
|
+
}
|
|
63
|
+
const asset = await host.sdk.assets.write({ relativePath: `studio/music/imports/${crypto.randomUUID()}/${kind}.${extension}`, body: chunks(), mediaType: mimeType, overwrite: false });
|
|
64
|
+
update(kind === 'source'
|
|
65
|
+
? { ...remaining, sourceRelativePath: asset.relativePath, sourceName: file.name, sourceMimeType: mimeType }
|
|
66
|
+
: { ...remaining, targetKind: 'reference-audio', targetRelativePath: asset.relativePath, targetName: file.name, targetMimeType: mimeType });
|
|
67
|
+
} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
|
|
68
|
+
finally { setBusy(null); }
|
|
69
|
+
}
|
|
70
|
+
function updateSemitone(next: StudioVoiceConvertParameters) {
|
|
71
|
+
const value = next.semitoneShift;
|
|
72
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value < -12 || value > 12)) { setError(t('VoiceConvert.semitoneInvalid')); return; }
|
|
73
|
+
setError(''); update(next);
|
|
74
|
+
}
|
|
75
|
+
return <div className="space-y-4">
|
|
76
|
+
{!profile ? <p>{t('VoiceConvert.configureInputs')}</p> : <p>{t('VoiceConvert.inputHint', {
|
|
77
|
+
sourceSeconds: profile.maxSourceSeconds, sourceMib: Math.floor(profile.maxSourceBytes / 1048576),
|
|
78
|
+
targetSeconds: profile.maxTargetSeconds, targetMib: Math.floor(profile.maxTargetBytes / 1048576) })}</p>}
|
|
79
|
+
<StudioParameterField label={t('VoiceConvert.source')}>
|
|
80
|
+
<input ref={sourceInput} hidden type="file" accept=".mp3,.wav,.flac" onChange={event => {
|
|
81
|
+
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (file) void importAudio(file, 'source');
|
|
82
|
+
}} />
|
|
83
|
+
<Button disabled={disabled || !profile} onClick={() => sourceInput.current?.click()}>{t(busy === 'source' ? 'Music.importing' : 'VoiceConvert.chooseSource')}</Button>
|
|
84
|
+
{parameters.sourceRelativePath ? <p>{parameters.sourceName}</p> : null}
|
|
85
|
+
</StudioParameterField>
|
|
86
|
+
{profile ? <>
|
|
87
|
+
{profile.supportsRange ? <>
|
|
88
|
+
<StudioNumberParameter current={parameters} field="sourceStartSeconds" label={t('VoiceConvert.sourceStart')} onChange={update} disabled={disabled} />
|
|
89
|
+
<StudioNumberParameter current={parameters} field="sourceEndSeconds" label={t('VoiceConvert.sourceEnd')} onChange={update} disabled={disabled} />
|
|
90
|
+
<p className="text-sm opacity-70">{t('VoiceConvert.rangeHint')}</p>
|
|
91
|
+
</> : null}
|
|
92
|
+
<StudioParameterField label={t('VoiceConvert.targetKind')}>
|
|
93
|
+
<SelectField value={targetKind} disabled={disabled}
|
|
94
|
+
options={[...new Set(profiles.flatMap(item => item.targetKinds))].map(value => ({ value, label: t(`VoiceConvert.targetKinds.${value}`) }))}
|
|
95
|
+
onValueChange={value => {
|
|
96
|
+
const { targetRelativePath, targetName, targetMimeType, targetStartSeconds, targetEndSeconds, targetPresetVoiceId, targetVoiceAssetId, ...rest } = parameters;
|
|
97
|
+
update({ ...rest, targetKind: value as VoiceTargetKind });
|
|
98
|
+
}} />
|
|
99
|
+
</StudioParameterField>
|
|
100
|
+
{targetKind === 'reference-audio' ? <>
|
|
101
|
+
<StudioParameterField label={t('VoiceConvert.target')}>
|
|
102
|
+
<input ref={targetInput} hidden type="file" accept=".mp3,.wav,.flac" onChange={event => {
|
|
103
|
+
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (file) void importAudio(file, 'target');
|
|
104
|
+
}} />
|
|
105
|
+
<Button disabled={disabled || !profile} onClick={() => targetInput.current?.click()}>{t(busy === 'target' ? 'Music.importing' : 'VoiceConvert.chooseTarget')}</Button>
|
|
106
|
+
{parameters.targetRelativePath ? <p>{parameters.targetName}</p> : null}
|
|
107
|
+
</StudioParameterField>
|
|
108
|
+
{profile.supportsRange ? <>
|
|
109
|
+
<StudioNumberParameter current={parameters} field="targetStartSeconds" label={t('VoiceConvert.targetStart')} onChange={update} disabled={disabled} />
|
|
110
|
+
<StudioNumberParameter current={parameters} field="targetEndSeconds" label={t('VoiceConvert.targetEnd')} onChange={update} disabled={disabled} />
|
|
111
|
+
<p className="text-sm opacity-70">{t('VoiceConvert.rangeHint')}</p>
|
|
112
|
+
</> : null}
|
|
113
|
+
</> : targetKind === 'preset' ? (
|
|
114
|
+
<StudioTextParameter current={parameters} field="targetPresetVoiceId" label={t('VoiceConvert.presetVoiceId')} onChange={next => update({ ...next, targetKind: 'preset' })} disabled={disabled} />
|
|
115
|
+
) : (
|
|
116
|
+
<StudioParameterField label={t('VoiceConvert.voiceAsset')}>
|
|
117
|
+
<SelectField value={parameters.targetVoiceAssetId ?? ''} disabled={disabled || voices.length === 0}
|
|
118
|
+
placeholder={voices.length ? t('VoiceConvert.selectVoiceAsset') : t('VoiceConvert.noVoiceAssets')}
|
|
119
|
+
options={voices.map(voice => ({ value: voice.voiceAssetId, label: `${voice.voiceAssetId} · ${voice.creationSource} · ${voice.status}` }))}
|
|
120
|
+
onValueChange={value => update({ ...parameters, targetKind: 'voice-asset', targetVoiceAssetId: value })} />
|
|
121
|
+
</StudioParameterField>
|
|
122
|
+
)}
|
|
123
|
+
{profile.supportsSemitoneShift || parameters.semitoneShift !== undefined ? <>
|
|
124
|
+
<StudioNumberParameter current={parameters} field="semitoneShift" label={t('VoiceConvert.semitone')} onChange={updateSemitone}
|
|
125
|
+
disabled={disabled} min={profile.minSemitoneShift} max={profile.maxSemitoneShift} step={1} />
|
|
126
|
+
<p className="text-sm opacity-70">{t('VoiceConvert.semitoneHint')}</p>
|
|
127
|
+
</> : null}
|
|
128
|
+
</> : null}
|
|
129
|
+
<p className="text-sm opacity-70">{t('VoiceConvert.preparationHint')}</p>
|
|
130
|
+
{error ? <p role="alert">{error}</p> : null}
|
|
131
|
+
</div>;
|
|
132
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import type { NimiLocalAppAudioInfo, NimiLocalAppVoiceConvertTargetVoice } from '@nimiplatform/sdk/app';
|
|
2
|
+
import { beginStudioJobRecovery, recordedStudioScenarioJobClient, recoverStudioJobId, readStudioJobRecovery, restoreSavedStudioJobResult, saveStudioJobRecoveryResult, studioJobRecoverySignal } from '../../ai-studio-core/job-recovery.js';
|
|
3
|
+
import { createStudioScenarioJobClient, projectStudioArtifactRunnerResult, type StudioCapabilityRuntimeContext } from '../../ai-studio-core/runtime.js';
|
|
4
|
+
import type { StudioManagedArtifact } from '../../ai-studio-core/runtime-types.js';
|
|
5
|
+
import type { StudioVoiceConvertParameters } from './parameters.js';
|
|
6
|
+
|
|
7
|
+
// @nimi-authority: rule.nimi.runtime.ai-provider.voice-conversion
|
|
8
|
+
export async function runVoiceConvert(context: StudioCapabilityRuntimeContext) {
|
|
9
|
+
const parameters = context.input.parameters as StudioVoiceConvertParameters | undefined;
|
|
10
|
+
const client = context.host.client; const signal = context.input.signal;
|
|
11
|
+
if (parameters?.recoverySubmissionId) {
|
|
12
|
+
const entry = (await readStudioJobRecovery(client.storage, 'audio.voice.convert')).find(item => item.clientSubmissionId === parameters.recoverySubmissionId);
|
|
13
|
+
if (!entry?.sourceAudio) throw new Error(context.host.translate('Music.recoveryMissing'));
|
|
14
|
+
const saved = await restoreSavedStudioJobResult(entry, context.capability.label, 'audio.voice.convert', client.storage.assets, studioJobRecoverySignal(context.input));
|
|
15
|
+
if (saved) return saved;
|
|
16
|
+
const recoveredJobId = await recoverStudioJobId(client, entry, 'audio.voice.convert');
|
|
17
|
+
const result = await context.host.runners.voiceConversionObserve({ runtime: { ai: createStudioScenarioJobClient(context) },
|
|
18
|
+
jobId: recoveredJobId, signal: context.input.observationSignal, cancelSignal: signal, onObservation: context.input.onObservation, abortReason: context.host.abortReason, onJobUpdate: context.input.onJobUpdate });
|
|
19
|
+
const projected = await projectStudioArtifactRunnerResult({ ...context, voiceSourceVocal: entry.sourceAudio, voiceTargetAudio: entry.targetAudio }, result);
|
|
20
|
+
await saveStudioJobRecoveryResult(client.storage, entry.clientSubmissionId, projected, 'audio.voice.convert');
|
|
21
|
+
return projected;
|
|
22
|
+
}
|
|
23
|
+
const invalid = () => context.host.nonSuccess(context.capability, 'input-invalid', context.host.translate('VoiceConvert.configureInputs'));
|
|
24
|
+
const targetKind = parameters?.targetKind;
|
|
25
|
+
const presetVoiceId = parameters?.targetPresetVoiceId?.trim();
|
|
26
|
+
const voiceAssetId = parameters?.targetVoiceAssetId?.trim();
|
|
27
|
+
if (!parameters?.sourceRelativePath || !parameters.sourceMimeType || !targetKind) return invalid();
|
|
28
|
+
if (targetKind === 'reference-audio' ? !parameters.targetRelativePath || !parameters.targetMimeType
|
|
29
|
+
: targetKind === 'preset' ? !presetVoiceId
|
|
30
|
+
: targetKind === 'voice-asset' ? !voiceAssetId
|
|
31
|
+
: true) return invalid();
|
|
32
|
+
const semitoneShift = parameters.semitoneShift;
|
|
33
|
+
if (semitoneShift !== undefined && (!Number.isSafeInteger(semitoneShift) || semitoneShift < -12 || semitoneShift > 12)) return invalid();
|
|
34
|
+
const snapshot = await client.aiConfig.get();
|
|
35
|
+
const selection = snapshot.effectiveSelections.find(item => item.capabilityContract === 'audio.voice.convert');
|
|
36
|
+
const resource = selection?.resource;
|
|
37
|
+
const capabilities = resource?.oneofKind === 'local' ? resource.local.musicInput : undefined;
|
|
38
|
+
const hasRange = parameters.sourceStartSeconds !== undefined || parameters.sourceEndSeconds !== undefined
|
|
39
|
+
|| parameters.targetStartSeconds !== undefined || parameters.targetEndSeconds !== undefined;
|
|
40
|
+
const profile = capabilities?.voiceConvert?.find(item => item.sourceKinds.includes('singing') && item.targetKinds.includes(targetKind)
|
|
41
|
+
&& (semitoneShift === undefined || semitoneShift === 0 || (item.supportsSemitoneShift && semitoneShift >= item.minSemitoneShift && semitoneShift <= item.maxSemitoneShift))
|
|
42
|
+
&& (!hasRange || item.supportsRange));
|
|
43
|
+
if (selection?.state !== 'ready' || !profile) return invalid();
|
|
44
|
+
const original = await client.storage.assets.stat(parameters.sourceRelativePath);
|
|
45
|
+
if (original.sizeBytes < 1 || original.sizeBytes > profile.maxSourceBytes || original.mediaType !== parameters.sourceMimeType) return invalid();
|
|
46
|
+
signal?.throwIfAborted();
|
|
47
|
+
// Runtime owns decoding and the frame basis. These unary preparations cannot
|
|
48
|
+
// be interrupted by the App; cancellation abandons submission when they settle.
|
|
49
|
+
const preparedSource = await client.ai.artifacts.upload({ source: { kind: 'app-asset', relativePath: original.relativePath },
|
|
50
|
+
mimeType: parameters.sourceMimeType, audioPreparation: { profile: 'canonical-pcm-v1' } });
|
|
51
|
+
signal?.throwIfAborted();
|
|
52
|
+
const sourceInfo = preparedSource.audioInfo;
|
|
53
|
+
if (!sourceInfo || preparedSource.mimeType !== 'audio/wav' || sourceInfo.frameCount / sourceInfo.sampleRateHz > profile.maxSourceSeconds) return invalid();
|
|
54
|
+
const sourceRangeResult = resolveRange(parameters.sourceStartSeconds, parameters.sourceEndSeconds, sourceInfo);
|
|
55
|
+
if (sourceRangeResult === 'invalid') return invalid();
|
|
56
|
+
const sourceRange = sourceRangeResult;
|
|
57
|
+
let preparedTarget: typeof preparedSource | undefined;
|
|
58
|
+
let targetRange: { startFrame: number; endFrame: number } | undefined;
|
|
59
|
+
if (targetKind === 'reference-audio') {
|
|
60
|
+
const originalTarget = await client.storage.assets.stat(parameters.targetRelativePath!);
|
|
61
|
+
if (originalTarget.sizeBytes < 1 || originalTarget.sizeBytes > profile.maxTargetBytes || originalTarget.mediaType !== parameters.targetMimeType) return invalid();
|
|
62
|
+
signal?.throwIfAborted();
|
|
63
|
+
preparedTarget = await client.ai.artifacts.upload({ source: { kind: 'app-asset', relativePath: originalTarget.relativePath },
|
|
64
|
+
mimeType: parameters.targetMimeType!, audioPreparation: { profile: 'canonical-pcm-v1' } });
|
|
65
|
+
signal?.throwIfAborted();
|
|
66
|
+
if (preparedTarget.artifactId === preparedSource.artifactId) {
|
|
67
|
+
return context.host.nonSuccess(context.capability, 'input-invalid', context.host.translate('VoiceConvert.sameInput'));
|
|
68
|
+
}
|
|
69
|
+
const targetInfo = preparedTarget.audioInfo;
|
|
70
|
+
if (!targetInfo || preparedTarget.mimeType !== 'audio/wav' || targetInfo.frameCount / targetInfo.sampleRateHz > profile.maxTargetSeconds) return invalid();
|
|
71
|
+
const targetRangeResult = resolveRange(parameters.targetStartSeconds, parameters.targetEndSeconds, targetInfo);
|
|
72
|
+
if (targetRangeResult === 'invalid') return invalid();
|
|
73
|
+
targetRange = targetRangeResult;
|
|
74
|
+
}
|
|
75
|
+
const targetVoice: NimiLocalAppVoiceConvertTargetVoice = targetKind === 'reference-audio'
|
|
76
|
+
? { kind: 'reference-audio', artifactId: preparedTarget!.artifactId, ...(targetRange ? { range: targetRange } : {}) }
|
|
77
|
+
: targetKind === 'preset' ? { kind: 'preset', presetVoiceId: presetVoiceId! }
|
|
78
|
+
: { kind: 'voice-asset', voiceAssetId: voiceAssetId! };
|
|
79
|
+
const adopted = await client.storage.assets.adoptArtifact({ artifactId: preparedSource.artifactId,
|
|
80
|
+
relativePath: `studio/music/voice-convert-inputs/${crypto.randomUUID()}/source.wav`, overwrite: false });
|
|
81
|
+
let adoptedTarget: typeof adopted | undefined;
|
|
82
|
+
try {
|
|
83
|
+
if (preparedTarget) adoptedTarget = await client.storage.assets.adoptArtifact({ artifactId: preparedTarget.artifactId,
|
|
84
|
+
relativePath: `studio/music/voice-convert-inputs/${crypto.randomUUID()}/target.wav`, overwrite: false });
|
|
85
|
+
} catch (cause) { await client.storage.assets.remove(adopted.relativePath); throw cause; }
|
|
86
|
+
const sourceVocal: StudioManagedArtifact = { relativePath: adopted.relativePath, mediaType: adopted.mediaType,
|
|
87
|
+
sizeBytes: adopted.sizeBytes, sha256: adopted.sha256, displayName: parameters.sourceName, previewSource: 'managed-asset' };
|
|
88
|
+
const targetAudio: StudioManagedArtifact | undefined = adoptedTarget ? { relativePath: adoptedTarget.relativePath, mediaType: adoptedTarget.mediaType,
|
|
89
|
+
sizeBytes: adoptedTarget.sizeBytes, sha256: adoptedTarget.sha256, displayName: parameters.targetName, previewSource: 'managed-asset' } : undefined;
|
|
90
|
+
let clientSubmissionId: string;
|
|
91
|
+
try {
|
|
92
|
+
signal?.throwIfAborted();
|
|
93
|
+
if (adopted.sizeBytes !== preparedSource.sizeBytes || adopted.mediaType !== preparedSource.mimeType) throw new Error('Canonical source adoption changed metadata');
|
|
94
|
+
if (preparedTarget && adoptedTarget
|
|
95
|
+
&& (adoptedTarget.sizeBytes !== preparedTarget.sizeBytes || adoptedTarget.mediaType !== preparedTarget.mimeType)) throw new Error('Canonical target adoption changed metadata');
|
|
96
|
+
clientSubmissionId = await beginStudioJobRecovery(client.storage, 'audio.voice.convert', sourceVocal, targetAudio,
|
|
97
|
+
undefined, context.input.recordedRunConfig, context.input.prompt);
|
|
98
|
+
} catch (cause) {
|
|
99
|
+
if (adoptedTarget) await client.storage.assets.remove(adoptedTarget.relativePath);
|
|
100
|
+
await client.storage.assets.remove(adopted.relativePath);
|
|
101
|
+
throw cause;
|
|
102
|
+
}
|
|
103
|
+
const scenarioClient = recordedStudioScenarioJobClient(context, clientSubmissionId, 'audio.voice.convert');
|
|
104
|
+
const result = await context.host.runners.voiceConvert({ runtime: { ai: scenarioClient }, appId: context.host.appId,
|
|
105
|
+
sourceVocal: { artifactId: preparedSource.artifactId, ...(sourceRange ? { range: sourceRange } : {}) },
|
|
106
|
+
sourceKind: 'singing', targetVoice, ...(semitoneShift ? { semitoneShift } : {}),
|
|
107
|
+
scenarioId: context.scenarioId, surfaceId: context.host.surfaceId,
|
|
108
|
+
signal, observationSignal: context.input.observationSignal, onObservation: context.input.onObservation, abortReason: context.host.abortReason, onJobUpdate: context.input.onJobUpdate });
|
|
109
|
+
const projected = await projectStudioArtifactRunnerResult({ ...context, voiceSourceVocal: sourceVocal, voiceTargetAudio: targetAudio }, result);
|
|
110
|
+
await saveStudioJobRecoveryResult(client.storage, clientSubmissionId, projected, 'audio.voice.convert');
|
|
111
|
+
return projected;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function resolveRange(startSeconds: number | undefined, endSeconds: number | undefined, info: NimiLocalAppAudioInfo) {
|
|
115
|
+
if (startSeconds === undefined && endSeconds === undefined) return undefined;
|
|
116
|
+
const startFrame = Math.round((startSeconds ?? 0) * info.sampleRateHz);
|
|
117
|
+
const endFrame = endSeconds === undefined ? info.frameCount : Math.round(endSeconds * info.sampleRateHz);
|
|
118
|
+
if (!Number.isSafeInteger(startFrame) || !Number.isSafeInteger(endFrame) || startFrame < 0 || startFrame >= endFrame || endFrame > info.frameCount) return 'invalid';
|
|
119
|
+
return { startFrame, endFrame };
|
|
120
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// Shared by request dispatch and saved-request restoration.
|
|
2
|
+
export function isHttpsUrl(value: string): boolean {
|
|
3
|
+
try {
|
|
4
|
+
return new URL(value).protocol === 'https:';
|
|
5
|
+
} catch {
|
|
6
|
+
return false;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function audioMimeTypeFromUrl(value: string): string | null {
|
|
11
|
+
try {
|
|
12
|
+
const url = new URL(value);
|
|
13
|
+
if (url.protocol !== 'https:') return null;
|
|
14
|
+
const extension = url.pathname.split('.').pop()?.toLowerCase();
|
|
15
|
+
if (extension === 'wav') return 'audio/wav';
|
|
16
|
+
if (extension === 'mp3') return 'audio/mpeg';
|
|
17
|
+
if (extension === 'm4a') return 'audio/mp4';
|
|
18
|
+
if (extension === 'ogg') return 'audio/ogg';
|
|
19
|
+
if (extension === 'webm') return 'audio/webm';
|
|
20
|
+
if (extension === 'flac') return 'audio/flac';
|
|
21
|
+
return null;
|
|
22
|
+
} catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
@@ -59,9 +59,9 @@
|
|
|
59
59
|
},
|
|
60
60
|
"parameters": {
|
|
61
61
|
"voicePreset": "Preset voice",
|
|
62
|
-
"voiceAsset": "
|
|
63
|
-
"selectVoiceAsset": "Select a
|
|
64
|
-
"noVoiceAssets": "No
|
|
62
|
+
"voiceAsset": "Created voice",
|
|
63
|
+
"selectVoiceAsset": "Select a created voice",
|
|
64
|
+
"noVoiceAssets": "No created voices",
|
|
65
65
|
"chooseAudioFile": "Choose audio file",
|
|
66
66
|
"removeFile": "Remove",
|
|
67
67
|
"audioFileTooLarge": "Audio files must not exceed 32 MiB.",
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
"fields": {
|
|
73
73
|
"voiceSource": "Voice source",
|
|
74
74
|
"voicePreset": "Preset voice ID",
|
|
75
|
-
"voiceAsset": "
|
|
75
|
+
"voiceAsset": "Created voice",
|
|
76
76
|
"language": "Language",
|
|
77
77
|
"audioFormat": "Audio format",
|
|
78
78
|
"sampleRateHz": "Sample rate (Hz)",
|
|
@@ -59,9 +59,9 @@
|
|
|
59
59
|
},
|
|
60
60
|
"parameters": {
|
|
61
61
|
"voicePreset": "预设语音",
|
|
62
|
-
"voiceAsset": "
|
|
63
|
-
"selectVoiceAsset": "
|
|
64
|
-
"noVoiceAssets": "
|
|
62
|
+
"voiceAsset": "已创建音色",
|
|
63
|
+
"selectVoiceAsset": "选择已创建音色",
|
|
64
|
+
"noVoiceAssets": "暂无已创建音色",
|
|
65
65
|
"chooseAudioFile": "选择音频文件",
|
|
66
66
|
"removeFile": "移除",
|
|
67
67
|
"audioFileTooLarge": "音频文件不得超过 32 MiB。",
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
"fields": {
|
|
73
73
|
"voiceSource": "语音来源",
|
|
74
74
|
"voicePreset": "预设语音 ID",
|
|
75
|
-
"voiceAsset": "
|
|
75
|
+
"voiceAsset": "已创建音色",
|
|
76
76
|
"language": "语言",
|
|
77
77
|
"audioFormat": "音频格式",
|
|
78
78
|
"sampleRateHz": "采样率(Hz)",
|
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
SUPPORTED_STUDIO_PARAMETER,
|
|
5
5
|
defineStudioParameters,
|
|
6
6
|
} from '../../ai-studio-core/parameters.js';
|
|
7
|
+
import { audioMimeTypeFromUrl, isHttpsUrl } from './audio-url.js';
|
|
7
8
|
|
|
8
9
|
export type StudioSpeechSynthesizeParameters = {
|
|
9
10
|
voiceKind?: 'preset' | 'asset';
|
|
@@ -49,39 +50,64 @@ export type StudioVoiceCreateParameters = {
|
|
|
49
50
|
export const MAX_STUDIO_AUDIO_UPLOAD_BYTES = 32 * 1024 * 1024;
|
|
50
51
|
export const MAX_STUDIO_VOICE_REFERENCE_AUDIO_BYTES = 20 * 1024 * 1024;
|
|
51
52
|
|
|
52
|
-
const LOCAL_PRESET_CLOUD_CONFIGURABLE = Object.freeze({
|
|
53
|
-
local: { kind: 'fixed', value: 'preset' } as const,
|
|
54
|
-
cloud: SUPPORTED_STUDIO_PARAMETER,
|
|
55
|
-
});
|
|
56
53
|
const LOCAL_TEXT_CLOUD_CONFIGURABLE = Object.freeze({
|
|
57
54
|
local: { kind: 'fixed', value: 'text' } as const,
|
|
58
55
|
cloud: SUPPORTED_STUDIO_PARAMETER,
|
|
59
56
|
});
|
|
60
57
|
|
|
58
|
+
// Route-level availability does not promise support from every selected model.
|
|
59
|
+
// Runtime validates the exact voice, format, language and timing request.
|
|
61
60
|
export const studioSpeechSynthesizeParameters = defineStudioParameters<StudioSpeechSynthesizeParameters>({
|
|
62
61
|
initial: () => ({}),
|
|
62
|
+
restoreRecordedParameters: (snapshot) => {
|
|
63
|
+
if (!snapshot) return null;
|
|
64
|
+
const strings = new Set(['voiceKind', 'voicePreset', 'voiceAssetId', 'language', 'audioFormat', 'emotion', 'timingMode']);
|
|
65
|
+
const numbers = new Set(['sampleRateHz', 'speed', 'pitch', 'volume']);
|
|
66
|
+
for (const [key, value] of Object.entries(snapshot)) {
|
|
67
|
+
if (strings.has(key)) { if (typeof value !== 'string') return null; }
|
|
68
|
+
else if (numbers.has(key)) { if (typeof value !== 'number' || !Number.isFinite(value)) return null; }
|
|
69
|
+
else return null;
|
|
70
|
+
}
|
|
71
|
+
if (snapshot.voiceKind !== undefined && snapshot.voiceKind !== 'preset' && snapshot.voiceKind !== 'asset') return null;
|
|
72
|
+
if (snapshot.timingMode !== undefined && !['unspecified', 'none', 'word', 'char'].includes(String(snapshot.timingMode))) return null;
|
|
73
|
+
return { ...snapshot } as StudioSpeechSynthesizeParameters;
|
|
74
|
+
},
|
|
63
75
|
routeMatrix: {
|
|
64
|
-
voiceKind:
|
|
76
|
+
voiceKind: LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
65
77
|
voicePreset: LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
66
|
-
voiceAssetId:
|
|
67
|
-
language:
|
|
68
|
-
audioFormat:
|
|
78
|
+
voiceAssetId: LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
79
|
+
language: LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
80
|
+
audioFormat: LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
69
81
|
sampleRateHz: CLOUD_ONLY_STUDIO_PARAMETER,
|
|
70
82
|
speed: CLOUD_ONLY_STUDIO_PARAMETER,
|
|
71
83
|
pitch: CLOUD_ONLY_STUDIO_PARAMETER,
|
|
72
84
|
volume: CLOUD_ONLY_STUDIO_PARAMETER,
|
|
73
85
|
emotion: CLOUD_ONLY_STUDIO_PARAMETER,
|
|
74
|
-
timingMode:
|
|
86
|
+
timingMode: LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
75
87
|
},
|
|
76
88
|
});
|
|
77
89
|
|
|
78
90
|
export const studioSpeechTranscribeParameters = defineStudioParameters<StudioSpeechTranscribeParameters>({
|
|
79
91
|
initial: () => ({}),
|
|
92
|
+
restoreRecordedParameters: (snapshot, _result, recordedPrompt) => {
|
|
93
|
+
// File history retains a label, not bytes. Only a saved HTTPS URL and
|
|
94
|
+
// its complete scalar request can be replayed without a new selection.
|
|
95
|
+
if (!snapshot || !recordedPrompt || !isHttpsUrl(recordedPrompt)) return null;
|
|
96
|
+
const strings = new Set(['mimeType', 'language', 'prompt', 'responseFormat']);
|
|
97
|
+
for (const [key, value] of Object.entries(snapshot)) {
|
|
98
|
+
if (strings.has(key)) { if (typeof value !== 'string') return null; }
|
|
99
|
+
else if (key === 'timestamps' || key === 'diarization') { if (typeof value !== 'boolean') return null; }
|
|
100
|
+
else if (key === 'speakerCount') { if (!Number.isSafeInteger(value) || Number(value) < 0 || Number(value) > 32) return null; }
|
|
101
|
+
else return null;
|
|
102
|
+
}
|
|
103
|
+
if (!String(snapshot.mimeType ?? '').trim() && !audioMimeTypeFromUrl(recordedPrompt)) return null;
|
|
104
|
+
return { ...snapshot } as StudioSpeechTranscribeParameters;
|
|
105
|
+
},
|
|
80
106
|
routeMatrix: {
|
|
81
107
|
audioFile: LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
82
108
|
mimeType: LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
83
109
|
language: LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
84
|
-
timestamps:
|
|
110
|
+
timestamps: LOCAL_AND_CLOUD_STUDIO_PARAMETER,
|
|
85
111
|
diarization: CLOUD_ONLY_STUDIO_PARAMETER,
|
|
86
112
|
speakerCount: CLOUD_ONLY_STUDIO_PARAMETER,
|
|
87
113
|
prompt: CLOUD_ONLY_STUDIO_PARAMETER,
|