@xsai/audio 0.0.0-stage → 1.0.0-beta.1
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/LICENSE.md +21 -0
- package/README.md +25 -2
- package/dist/index.d.ts +114 -0
- package/dist/index.js +193 -0
- package/package.json +43 -3
package/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Moeru AI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,26 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @xsai/audio
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<!-- automd:file src="/docs/snippets/audio.md" -->
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pnpm add @xsai/audio
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { writeFile } from 'node:fs/promises'
|
|
11
|
+
|
|
12
|
+
import { generateSpeech, speech } from '@xsai/audio'
|
|
13
|
+
|
|
14
|
+
const model = speech({
|
|
15
|
+
apiKey: process.env.OPENAI_API_KEY,
|
|
16
|
+
baseURL: 'https://api.openai.com/v1/',
|
|
17
|
+
model: 'YOUR_SPEECH_MODEL_ID',
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
const audio = await generateSpeech(model, { input: 'Welcome to the forest.', voice: 'alloy' })
|
|
21
|
+
await writeFile('speech.mp3', new Uint8Array(await audio.arrayBuffer()))
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
<!-- /automd -->
|
|
25
|
+
|
|
26
|
+
Read the [documentation](https://xsai.js.org/audio).
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { Promisable, HttpOptions } from '@xsai/shared';
|
|
2
|
+
|
|
3
|
+
type SpeechModel = (options: SpeechModelOptions) => Promisable<Response>;
|
|
4
|
+
interface SpeechModelOptions {
|
|
5
|
+
input: string;
|
|
6
|
+
providerOptions?: SpeechModelProviderOptions;
|
|
7
|
+
signal?: AbortSignal;
|
|
8
|
+
voice: string;
|
|
9
|
+
}
|
|
10
|
+
interface SpeechModelProviderOptions {
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
declare const generateSpeech: (model: SpeechModel, options: SpeechModelOptions) => Promise<Blob>;
|
|
14
|
+
|
|
15
|
+
declare module '@xsai/audio' {
|
|
16
|
+
interface SpeechModelProviderOptions {
|
|
17
|
+
speech?: {
|
|
18
|
+
instructions?: string;
|
|
19
|
+
outputFormat?: 'aac' | 'flac' | 'mp3' | 'opus' | 'wav';
|
|
20
|
+
speed?: number;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
declare const speech: (options: HttpOptions) => SpeechModel;
|
|
25
|
+
|
|
26
|
+
declare const streamSpeech: (model: SpeechModel, options: SpeechModelOptions) => Promise<Response>;
|
|
27
|
+
|
|
28
|
+
interface TranscriptionEndEvent extends TranscriptionResult {
|
|
29
|
+
type: 'transcription.end';
|
|
30
|
+
}
|
|
31
|
+
type TranscriptionEvent = TranscriptionEndEvent | TranscriptionStartEvent | TranscriptionTextDeltaEvent | TranscriptionTextSegmentEvent;
|
|
32
|
+
interface TranscriptionResult {
|
|
33
|
+
durationInSeconds?: number;
|
|
34
|
+
language?: string;
|
|
35
|
+
segments?: TranscriptionSegment[];
|
|
36
|
+
text: string;
|
|
37
|
+
words?: TranscriptionWord[];
|
|
38
|
+
}
|
|
39
|
+
interface TranscriptionSegment {
|
|
40
|
+
endSecond: number;
|
|
41
|
+
id?: string;
|
|
42
|
+
providerMetadata?: TranscriptionSegmentProviderMetadata;
|
|
43
|
+
startSecond: number;
|
|
44
|
+
text: string;
|
|
45
|
+
}
|
|
46
|
+
interface TranscriptionSegmentProviderMetadata {
|
|
47
|
+
}
|
|
48
|
+
interface TranscriptionStartEvent {
|
|
49
|
+
type: 'transcription.start';
|
|
50
|
+
}
|
|
51
|
+
interface TranscriptionTextDeltaEvent {
|
|
52
|
+
delta: string;
|
|
53
|
+
segmentId?: string;
|
|
54
|
+
type: 'transcription.text.delta';
|
|
55
|
+
}
|
|
56
|
+
interface TranscriptionTextSegmentEvent extends TranscriptionSegment {
|
|
57
|
+
type: 'transcription.text.segment';
|
|
58
|
+
}
|
|
59
|
+
interface TranscriptionWord {
|
|
60
|
+
endSecond: number;
|
|
61
|
+
providerMetadata?: TranscriptionWordProviderMetadata;
|
|
62
|
+
startSecond: number;
|
|
63
|
+
text: string;
|
|
64
|
+
}
|
|
65
|
+
interface TranscriptionWordProviderMetadata {
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
type TranscriptionModel = (options: TranscriptionModelOptions) => Promisable<ReadableStream<TranscriptionEvent>>;
|
|
69
|
+
interface TranscriptionModelOptions {
|
|
70
|
+
audio: Blob;
|
|
71
|
+
fileName?: string;
|
|
72
|
+
language?: string;
|
|
73
|
+
providerOptions?: TranscriptionModelProviderOptions;
|
|
74
|
+
signal?: AbortSignal;
|
|
75
|
+
}
|
|
76
|
+
interface TranscriptionModelProviderOptions {
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
declare const generateTranscription: (model: TranscriptionModel, options: TranscriptionModelOptions) => Promise<TranscriptionResult>;
|
|
80
|
+
|
|
81
|
+
declare module '@xsai/audio' {
|
|
82
|
+
interface TranscriptionModelProviderOptions {
|
|
83
|
+
transcriptions?: {
|
|
84
|
+
chunkingStrategy?: 'auto';
|
|
85
|
+
prompt?: string;
|
|
86
|
+
responseFormat?: 'diarized_json' | 'json' | 'verbose_json';
|
|
87
|
+
temperature?: number;
|
|
88
|
+
timestampGranularities?: ('segment' | 'word')[];
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
interface TranscriptionSegmentProviderMetadata {
|
|
92
|
+
transcriptions?: {
|
|
93
|
+
avgLogprob?: number;
|
|
94
|
+
compressionRatio?: number;
|
|
95
|
+
noSpeechProb?: number;
|
|
96
|
+
seek?: number;
|
|
97
|
+
speaker?: string;
|
|
98
|
+
temperature?: number;
|
|
99
|
+
tokens?: number[];
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
interface TranscriptionWordProviderMetadata {
|
|
103
|
+
transcriptions?: {
|
|
104
|
+
probability?: number;
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
declare const transcriptions: (options: HttpOptions) => TranscriptionModel;
|
|
109
|
+
declare const transcriptionsNonStreaming: (options: HttpOptions) => TranscriptionModel;
|
|
110
|
+
|
|
111
|
+
declare const streamTranscription: (model: TranscriptionModel, options: TranscriptionModelOptions) => Promise<ReadableStream<TranscriptionEvent>>;
|
|
112
|
+
|
|
113
|
+
export { generateSpeech, generateTranscription, speech, streamSpeech, streamTranscription, transcriptions, transcriptionsNonStreaming };
|
|
114
|
+
export type { SpeechModel, SpeechModelOptions, SpeechModelProviderOptions, TranscriptionEndEvent, TranscriptionEvent, TranscriptionModel, TranscriptionModelOptions, TranscriptionModelProviderOptions, TranscriptionResult, TranscriptionSegment, TranscriptionSegmentProviderMetadata, TranscriptionStartEvent, TranscriptionTextDeltaEvent, TranscriptionTextSegmentEvent, TranscriptionWord, TranscriptionWordProviderMetadata };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { sendRequest, XSAIError, EventSourceParserStream } from '@xsai/shared';
|
|
2
|
+
|
|
3
|
+
const streamSpeech = async (model, options) => model(options);
|
|
4
|
+
|
|
5
|
+
const generateSpeech = async (model, options) => streamSpeech(model, options).then(async (r) => r.blob());
|
|
6
|
+
|
|
7
|
+
const formats = {
|
|
8
|
+
aac: ["audio/aac"],
|
|
9
|
+
flac: ["audio/flac", "audio/x-flac"],
|
|
10
|
+
mp3: ["audio/mpeg", "audio/mp3"],
|
|
11
|
+
opus: ["audio/ogg"],
|
|
12
|
+
wav: ["audio/wav", "audio/x-wav", "audio/wave", "audio/vnd.wave"]
|
|
13
|
+
};
|
|
14
|
+
const speech = (options) => async (modelOptions) => {
|
|
15
|
+
const format = modelOptions.providerOptions?.speech?.outputFormat ?? "mp3";
|
|
16
|
+
const response = await sendRequest({
|
|
17
|
+
body: {
|
|
18
|
+
input: modelOptions.input,
|
|
19
|
+
instructions: modelOptions.providerOptions?.speech?.instructions,
|
|
20
|
+
model: options.model,
|
|
21
|
+
response_format: format,
|
|
22
|
+
speed: modelOptions.providerOptions?.speech?.speed,
|
|
23
|
+
stream_format: "audio",
|
|
24
|
+
voice: modelOptions.voice
|
|
25
|
+
},
|
|
26
|
+
path: "audio/speech",
|
|
27
|
+
signal: modelOptions.signal
|
|
28
|
+
}, options);
|
|
29
|
+
const contentType = response.headers.get("Content-Type");
|
|
30
|
+
const mime = contentType?.split(";", 1)[0]?.trim().toLowerCase();
|
|
31
|
+
const mediaTypes = formats[format];
|
|
32
|
+
if (mime == null || mime === "application/octet-stream") {
|
|
33
|
+
const headers = new Headers(response.headers);
|
|
34
|
+
headers.set("Content-Type", mediaTypes[0]);
|
|
35
|
+
return new Response(response.body, { headers, status: response.status, statusText: response.statusText });
|
|
36
|
+
}
|
|
37
|
+
if (!mediaTypes.includes(mime)) {
|
|
38
|
+
const error = new XSAIError("invalid-response", `Unexpected speech Content-Type: ${contentType}`);
|
|
39
|
+
await response.body.cancel(error).catch(() => {
|
|
40
|
+
});
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
return response;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const generateTranscription = async (model, options) => {
|
|
47
|
+
let result;
|
|
48
|
+
for await (const event of await model(options)) {
|
|
49
|
+
if (event.type === "transcription.end") {
|
|
50
|
+
const { type: _, ...value } = event;
|
|
51
|
+
result = value;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (result == null)
|
|
55
|
+
throw new XSAIError("truncated-stream", "model stream ended without a transcription.end event");
|
|
56
|
+
return result;
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const transcriptionBody = (model, options, streaming = false) => {
|
|
60
|
+
const wireOptions = options.providerOptions?.transcriptions;
|
|
61
|
+
const body = new FormData();
|
|
62
|
+
body.append("file", options.audio, options.fileName);
|
|
63
|
+
for (const [key, value] of Object.entries({
|
|
64
|
+
chunking_strategy: wireOptions?.chunkingStrategy,
|
|
65
|
+
language: options.language,
|
|
66
|
+
model,
|
|
67
|
+
prompt: wireOptions?.prompt,
|
|
68
|
+
response_format: wireOptions?.responseFormat ?? "json",
|
|
69
|
+
stream: streaming ? true : void 0,
|
|
70
|
+
temperature: wireOptions?.temperature
|
|
71
|
+
})) {
|
|
72
|
+
if (value != null)
|
|
73
|
+
body.append(key, String(value));
|
|
74
|
+
}
|
|
75
|
+
for (const granularity of wireOptions?.timestampGranularities ?? (wireOptions?.responseFormat === "verbose_json" ? ["segment"] : []))
|
|
76
|
+
body.append("timestamp_granularities[]", granularity);
|
|
77
|
+
return body;
|
|
78
|
+
};
|
|
79
|
+
const transcriptionSegment = (value) => {
|
|
80
|
+
const metadata = {
|
|
81
|
+
avgLogprob: value.avg_logprob,
|
|
82
|
+
compressionRatio: value.compression_ratio,
|
|
83
|
+
noSpeechProb: value.no_speech_prob,
|
|
84
|
+
seek: value.seek,
|
|
85
|
+
speaker: value.speaker,
|
|
86
|
+
temperature: value.temperature,
|
|
87
|
+
tokens: value.tokens
|
|
88
|
+
};
|
|
89
|
+
return {
|
|
90
|
+
endSecond: value.end,
|
|
91
|
+
id: value.id?.toString(),
|
|
92
|
+
providerMetadata: Object.values(metadata).some((value2) => value2 != null) ? { transcriptions: metadata } : void 0,
|
|
93
|
+
startSecond: value.start,
|
|
94
|
+
text: value.text
|
|
95
|
+
};
|
|
96
|
+
};
|
|
97
|
+
const transcriptionResult = (value) => {
|
|
98
|
+
if (value == null || typeof value !== "object" || !("text" in value) || typeof value.text !== "string")
|
|
99
|
+
throw new XSAIError("invalid-response", "Expected transcription text to be a string", { cause: value });
|
|
100
|
+
const result = value;
|
|
101
|
+
return {
|
|
102
|
+
durationInSeconds: result.duration,
|
|
103
|
+
language: result.language,
|
|
104
|
+
segments: result.segments?.map(transcriptionSegment),
|
|
105
|
+
text: result.text,
|
|
106
|
+
words: result.words?.map((word) => ({
|
|
107
|
+
endSecond: word.end,
|
|
108
|
+
providerMetadata: word.probability == null ? void 0 : { transcriptions: { probability: word.probability } },
|
|
109
|
+
startSecond: word.start,
|
|
110
|
+
text: word.word
|
|
111
|
+
}))
|
|
112
|
+
};
|
|
113
|
+
};
|
|
114
|
+
class TranscriptionEventStream extends TransformStream {
|
|
115
|
+
constructor() {
|
|
116
|
+
const segments = [];
|
|
117
|
+
super({
|
|
118
|
+
flush: () => {
|
|
119
|
+
throw new XSAIError("truncated-stream", "transcription stream ended without transcript.text.done");
|
|
120
|
+
},
|
|
121
|
+
start: (output) => output.enqueue({ type: "transcription.start" }),
|
|
122
|
+
transform: ({ data }, output) => {
|
|
123
|
+
if (data === "" || data === "[DONE]")
|
|
124
|
+
return;
|
|
125
|
+
const event = JSON.parse(data);
|
|
126
|
+
if (event == null || typeof event !== "object")
|
|
127
|
+
throw new XSAIError("invalid-response", "Expected a transcription event object", { cause: event });
|
|
128
|
+
if (event.type === "error" || "error" in event && event.error != null)
|
|
129
|
+
throw new XSAIError("invalid-response", "Transcription provider reported an error", { cause: "error" in event ? event.error : event });
|
|
130
|
+
if (event.type === "transcript.text.delta") {
|
|
131
|
+
output.enqueue({
|
|
132
|
+
delta: event.delta,
|
|
133
|
+
segmentId: event.segment_id,
|
|
134
|
+
type: "transcription.text.delta"
|
|
135
|
+
});
|
|
136
|
+
} else if (event.type === "transcript.text.segment") {
|
|
137
|
+
const segment = transcriptionSegment(event);
|
|
138
|
+
segments.push(segment);
|
|
139
|
+
output.enqueue({ ...segment, type: "transcription.text.segment" });
|
|
140
|
+
} else if (event.type === "transcript.text.done") {
|
|
141
|
+
const result = transcriptionResult(event);
|
|
142
|
+
output.enqueue({
|
|
143
|
+
...result,
|
|
144
|
+
segments: segments.length > 0 ? segments : result.segments,
|
|
145
|
+
type: "transcription.end"
|
|
146
|
+
});
|
|
147
|
+
output.terminate();
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
class TranscriptionResultStream extends TransformStream {
|
|
154
|
+
constructor() {
|
|
155
|
+
let text = "";
|
|
156
|
+
super({
|
|
157
|
+
flush: (output) => {
|
|
158
|
+
output.enqueue({ ...transcriptionResult(JSON.parse(text)), type: "transcription.end" });
|
|
159
|
+
},
|
|
160
|
+
start: (output) => output.enqueue({ type: "transcription.start" }),
|
|
161
|
+
transform: (chunk) => {
|
|
162
|
+
text += chunk;
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const transcriptions = (options) => async (modelOptions) => {
|
|
168
|
+
const response = await sendRequest({
|
|
169
|
+
body: transcriptionBody(options.model, modelOptions, true),
|
|
170
|
+
path: "audio/transcriptions",
|
|
171
|
+
signal: modelOptions.signal
|
|
172
|
+
}, options);
|
|
173
|
+
const mime = response.headers.get("Content-Type")?.split(";", 1)[0]?.trim().toLowerCase();
|
|
174
|
+
if (mime !== "text/event-stream") {
|
|
175
|
+
const error = new XSAIError("invalid-response", "Expected an SSE transcription response");
|
|
176
|
+
await response.body.cancel(error).catch(() => {
|
|
177
|
+
});
|
|
178
|
+
throw error;
|
|
179
|
+
}
|
|
180
|
+
return response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream()).pipeThrough(new TranscriptionEventStream(), { signal: modelOptions.signal });
|
|
181
|
+
};
|
|
182
|
+
const transcriptionsNonStreaming = (options) => async (modelOptions) => {
|
|
183
|
+
const response = await sendRequest({
|
|
184
|
+
body: transcriptionBody(options.model, modelOptions),
|
|
185
|
+
path: "audio/transcriptions",
|
|
186
|
+
signal: modelOptions.signal
|
|
187
|
+
}, options);
|
|
188
|
+
return response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TranscriptionResultStream(), { signal: modelOptions.signal });
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
const streamTranscription = async (model, options) => model(options);
|
|
192
|
+
|
|
193
|
+
export { generateSpeech, generateTranscription, speech, streamSpeech, streamTranscription, transcriptions, transcriptionsNonStreaming };
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xsai/audio",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"type": "module",
|
|
4
|
+
"version": "1.0.0-beta.1",
|
|
5
|
+
"description": "extra-small AI SDK: speech generation and transcription.",
|
|
6
|
+
"author": "Moeru AI",
|
|
7
|
+
"license": "MIT",
|
|
8
|
+
"homepage": "https://xsai.js.org",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/moeru-ai/xsai.git",
|
|
12
|
+
"directory": "packages/audio"
|
|
13
|
+
},
|
|
14
|
+
"bugs": "https://github.com/moeru-ai/xsai/issues",
|
|
15
|
+
"keywords": [
|
|
16
|
+
"xsai",
|
|
17
|
+
"ai",
|
|
18
|
+
"openai",
|
|
19
|
+
"speech",
|
|
20
|
+
"tts",
|
|
21
|
+
"transcription",
|
|
22
|
+
"stt",
|
|
23
|
+
"audio"
|
|
24
|
+
],
|
|
25
|
+
"sideEffects": false,
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"dist"
|
|
35
|
+
],
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@xsai/shared": "1.0.0-beta.1"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "pkgroll --clean-dist",
|
|
41
|
+
"test": "vitest run --exclude e2e/**",
|
|
42
|
+
"test:watch": "vitest"
|
|
43
|
+
},
|
|
44
|
+
"main": "./dist/index.js",
|
|
45
|
+
"types": "./dist/index.d.ts"
|
|
6
46
|
}
|