soma-voice 1.0.0
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 +85 -0
- package/manifest.md +11 -0
- package/package.json +61 -0
- package/src/api/service/index.ts +5 -0
- package/src/api/service/voice/Synthesize.ts +15 -0
- package/src/api/service/voice/Transcribe.ts +16 -0
- package/src/api/service/voice/synthesize/Stream.ts +15 -0
- package/src/api/service/voice/transcribe/Raw.ts +15 -0
- package/src/client/audio-conversion.ts +127 -0
- package/src/client/audio-processing.ts +153 -0
- package/src/client/browser-codec.ts +73 -0
- package/src/client/capabilities.ts +72 -0
- package/src/client/errors.ts +10 -0
- package/src/client/http.ts +237 -0
- package/src/client/index.ts +15 -0
- package/src/client/indexeddb-storage.ts +109 -0
- package/src/client/offline.ts +139 -0
- package/src/client/player.ts +117 -0
- package/src/client/realtime-stt.ts +261 -0
- package/src/client/recorder.ts +280 -0
- package/src/client/storage.ts +89 -0
- package/src/client/streaming-tts.ts +156 -0
- package/src/client/transports.ts +221 -0
- package/src/client/wav.ts +58 -0
- package/src/index.ts +1 -0
- package/src/server/concurrency.ts +75 -0
- package/src/server/config.ts +173 -0
- package/src/server/errors.ts +49 -0
- package/src/server/index.ts +9 -0
- package/src/server/raw-transcription.ts +70 -0
- package/src/server/runtime.ts +425 -0
- package/src/server/speech-stream.ts +176 -0
- package/src/server/streaming.ts +160 -0
- package/src/server/upload.ts +94 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
|
|
3
|
+
export const VoiceErrorCodes = {
|
|
4
|
+
CONFIG: 4601,
|
|
5
|
+
INVALID_REQUEST: 4602,
|
|
6
|
+
AUDIO_TOO_LARGE: 4603,
|
|
7
|
+
UNSUPPORTED_AUDIO: 4604,
|
|
8
|
+
TEXT_TOO_LONG: 4605,
|
|
9
|
+
INVALID_OPTION: 4606,
|
|
10
|
+
BUSY: 4607,
|
|
11
|
+
UPSTREAM: 4608,
|
|
12
|
+
TIMEOUT: 4609,
|
|
13
|
+
} as const;
|
|
14
|
+
|
|
15
|
+
export class VoiceServerError extends Error {
|
|
16
|
+
constructor(
|
|
17
|
+
public readonly code: number,
|
|
18
|
+
message: string,
|
|
19
|
+
public readonly status = 400,
|
|
20
|
+
) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.name = 'VoiceServerError';
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function errorResponse(error: unknown): Response {
|
|
27
|
+
const voiceError = error instanceof VoiceServerError
|
|
28
|
+
? error
|
|
29
|
+
: new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Voice service failed.', 502);
|
|
30
|
+
return Response.json({
|
|
31
|
+
ret: voiceError.code,
|
|
32
|
+
code: voiceError.code,
|
|
33
|
+
success: false,
|
|
34
|
+
message: voiceError.message,
|
|
35
|
+
msg: voiceError.message,
|
|
36
|
+
data: null,
|
|
37
|
+
}, { status: voiceError.status });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function successResponse<T>(data: T): Response {
|
|
41
|
+
return Response.json({
|
|
42
|
+
ret: 0,
|
|
43
|
+
code: 0,
|
|
44
|
+
success: true,
|
|
45
|
+
message: 'success',
|
|
46
|
+
msg: 'success',
|
|
47
|
+
data,
|
|
48
|
+
});
|
|
49
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
export * from './concurrency';
|
|
3
|
+
export * from './config';
|
|
4
|
+
export * from './errors';
|
|
5
|
+
export * from './raw-transcription';
|
|
6
|
+
export * from './runtime';
|
|
7
|
+
export * from './speech-stream';
|
|
8
|
+
export * from './streaming';
|
|
9
|
+
export * from './upload';
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
import type { VoiceConfig } from './config';
|
|
3
|
+
import { VoiceErrorCodes, VoiceServerError } from './errors';
|
|
4
|
+
import { transcribeDetailed, type ServerTranscriptionResult } from './runtime';
|
|
5
|
+
import { readBoundedStream } from './upload';
|
|
6
|
+
|
|
7
|
+
const EXTENSION_BY_MIME: Record<string, string> = {
|
|
8
|
+
'audio/wav': 'wav',
|
|
9
|
+
'audio/x-wav': 'wav',
|
|
10
|
+
'audio/mpeg': 'mp3',
|
|
11
|
+
'audio/webm': 'webm',
|
|
12
|
+
'audio/ogg': 'ogg',
|
|
13
|
+
'audio/mp4': 'm4a',
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export async function transcribeRaw(
|
|
17
|
+
request: Request,
|
|
18
|
+
config: VoiceConfig,
|
|
19
|
+
): Promise<ServerTranscriptionResult> {
|
|
20
|
+
const mimeType = (request.headers.get('content-type') ?? '').toLowerCase().split(';', 1)[0];
|
|
21
|
+
const extension = EXTENSION_BY_MIME[mimeType];
|
|
22
|
+
if (!extension) {
|
|
23
|
+
throw new VoiceServerError(VoiceErrorCodes.UNSUPPORTED_AUDIO, 'Unsupported audio MIME type.', 415);
|
|
24
|
+
}
|
|
25
|
+
const bytes = await readBoundedStream(request.body, {
|
|
26
|
+
maxBytes: config.maxAudioBytes,
|
|
27
|
+
contentLength: request.headers.get('content-length'),
|
|
28
|
+
signal: request.signal,
|
|
29
|
+
timeoutMs: config.timeoutMs,
|
|
30
|
+
});
|
|
31
|
+
if (!bytes.byteLength) {
|
|
32
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Audio body is empty.');
|
|
33
|
+
}
|
|
34
|
+
const audioBuffer = bytes.buffer.slice(
|
|
35
|
+
bytes.byteOffset,
|
|
36
|
+
bytes.byteOffset + bytes.byteLength,
|
|
37
|
+
) as ArrayBuffer;
|
|
38
|
+
const form = new FormData();
|
|
39
|
+
form.append('file', new Blob([audioBuffer], { type: mimeType }), `recording.${extension}`);
|
|
40
|
+
const language = request.headers.get('x-voice-language')?.trim();
|
|
41
|
+
const encodedPrompt = request.headers.get('x-voice-prompt')?.trim();
|
|
42
|
+
let prompt: string | undefined;
|
|
43
|
+
if (encodedPrompt) {
|
|
44
|
+
try {
|
|
45
|
+
prompt = decodeURIComponent(encodedPrompt);
|
|
46
|
+
} catch {
|
|
47
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid voice prompt.');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const responseFormat = request.headers.get('x-voice-response-format')?.trim();
|
|
51
|
+
if (language && (!/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(language)
|
|
52
|
+
|| language.length > 32)) {
|
|
53
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid voice language.');
|
|
54
|
+
}
|
|
55
|
+
if (prompt && [...prompt].length > 1_000) {
|
|
56
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Voice prompt is too long.');
|
|
57
|
+
}
|
|
58
|
+
if (responseFormat && !['json', 'verbose_json'].includes(responseFormat)) {
|
|
59
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid response format.');
|
|
60
|
+
}
|
|
61
|
+
if (language) form.append('language', language);
|
|
62
|
+
if (prompt) form.append('prompt', prompt);
|
|
63
|
+
if (responseFormat) form.append('response_format', responseFormat);
|
|
64
|
+
const forwarded = new Request(request.url, {
|
|
65
|
+
method: 'POST',
|
|
66
|
+
body: form,
|
|
67
|
+
signal: request.signal,
|
|
68
|
+
});
|
|
69
|
+
return transcribeDetailed(forwarded, config);
|
|
70
|
+
}
|
|
@@ -0,0 +1,425 @@
|
|
|
1
|
+
import 'server-only';
|
|
2
|
+
import type { VoiceConfig } from './config';
|
|
3
|
+
import { acquireVoicePermit } from './concurrency';
|
|
4
|
+
import { VoiceErrorCodes, VoiceServerError } from './errors';
|
|
5
|
+
|
|
6
|
+
const MAGIC: Record<string, (bytes: Uint8Array) => boolean> = {
|
|
7
|
+
'audio/wav': (bytes) => String.fromCharCode(...bytes.slice(0, 4)) === 'RIFF'
|
|
8
|
+
&& String.fromCharCode(...bytes.slice(8, 12)) === 'WAVE',
|
|
9
|
+
'audio/x-wav': (bytes) => String.fromCharCode(...bytes.slice(0, 4)) === 'RIFF'
|
|
10
|
+
&& String.fromCharCode(...bytes.slice(8, 12)) === 'WAVE',
|
|
11
|
+
'audio/mpeg': (bytes) => String.fromCharCode(...bytes.slice(0, 3)) === 'ID3'
|
|
12
|
+
|| (bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0),
|
|
13
|
+
'audio/webm': (bytes) => bytes[0] === 0x1a && bytes[1] === 0x45
|
|
14
|
+
&& bytes[2] === 0xdf && bytes[3] === 0xa3,
|
|
15
|
+
'audio/ogg': (bytes) => String.fromCharCode(...bytes.slice(0, 4)) === 'OggS',
|
|
16
|
+
'audio/mp4': (bytes) => String.fromCharCode(...bytes.slice(4, 8)) === 'ftyp',
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
interface BlobLike {
|
|
20
|
+
size: number;
|
|
21
|
+
type: string;
|
|
22
|
+
slice(start?: number, end?: number): Blob;
|
|
23
|
+
arrayBuffer(): Promise<ArrayBuffer>;
|
|
24
|
+
name?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function isBlobLike(value: unknown): value is BlobLike {
|
|
28
|
+
if (!value || typeof value !== 'object') return false;
|
|
29
|
+
const candidate = value as Partial<BlobLike>;
|
|
30
|
+
return typeof candidate.size === 'number'
|
|
31
|
+
&& typeof candidate.type === 'string'
|
|
32
|
+
&& typeof candidate.slice === 'function'
|
|
33
|
+
&& typeof candidate.arrayBuffer === 'function';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function validateAudio(file: BlobLike, max: number): Promise<void> {
|
|
37
|
+
if (!isBlobLike(file) || file.size < 4) {
|
|
38
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Audio file is empty.');
|
|
39
|
+
}
|
|
40
|
+
if (file.size > max) {
|
|
41
|
+
throw new VoiceServerError(VoiceErrorCodes.AUDIO_TOO_LARGE, 'Audio file is too large.', 413);
|
|
42
|
+
}
|
|
43
|
+
const mime = file.type.toLowerCase().split(';', 1)[0];
|
|
44
|
+
const check = MAGIC[mime];
|
|
45
|
+
if (!check) {
|
|
46
|
+
throw new VoiceServerError(VoiceErrorCodes.UNSUPPORTED_AUDIO, 'Unsupported audio MIME type.');
|
|
47
|
+
}
|
|
48
|
+
const bytes = new Uint8Array(await file.slice(0, 16).arrayBuffer());
|
|
49
|
+
if (!check(bytes)) {
|
|
50
|
+
throw new VoiceServerError(
|
|
51
|
+
VoiceErrorCodes.UNSUPPORTED_AUDIO,
|
|
52
|
+
'Audio content does not match MIME type.',
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function readLimited(response: Response, maxBytes: number): Promise<Uint8Array> {
|
|
58
|
+
const declared = Number(response.headers.get('content-length'));
|
|
59
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
60
|
+
await response.body?.cancel().catch(() => undefined);
|
|
61
|
+
throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Voice upstream response is too large.', 502);
|
|
62
|
+
}
|
|
63
|
+
if (!response.body) return new Uint8Array();
|
|
64
|
+
const reader = response.body.getReader();
|
|
65
|
+
const chunks: Uint8Array[] = [];
|
|
66
|
+
let total = 0;
|
|
67
|
+
try {
|
|
68
|
+
while (true) {
|
|
69
|
+
const { done, value } = await reader.read();
|
|
70
|
+
if (done) break;
|
|
71
|
+
total += value.byteLength;
|
|
72
|
+
if (total > maxBytes) {
|
|
73
|
+
await reader.cancel().catch(() => undefined);
|
|
74
|
+
throw new VoiceServerError(
|
|
75
|
+
VoiceErrorCodes.UPSTREAM,
|
|
76
|
+
'Voice upstream response is too large.',
|
|
77
|
+
502,
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
chunks.push(value);
|
|
81
|
+
}
|
|
82
|
+
} catch (error) {
|
|
83
|
+
await reader.cancel().catch(() => undefined);
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
const result = new Uint8Array(total);
|
|
87
|
+
let offset = 0;
|
|
88
|
+
for (const chunk of chunks) {
|
|
89
|
+
result.set(chunk, offset);
|
|
90
|
+
offset += chunk.byteLength;
|
|
91
|
+
}
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
async function discardErrorResponse(response: Response): Promise<void> {
|
|
96
|
+
if (!response.body) return;
|
|
97
|
+
const reader = response.body.getReader();
|
|
98
|
+
let read = 0;
|
|
99
|
+
try {
|
|
100
|
+
while (read < 8192) {
|
|
101
|
+
const { done, value } = await reader.read();
|
|
102
|
+
if (done) return;
|
|
103
|
+
read += value.byteLength;
|
|
104
|
+
}
|
|
105
|
+
} finally {
|
|
106
|
+
await reader.cancel().catch(() => undefined);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async function upstream<T>(
|
|
111
|
+
config: VoiceConfig,
|
|
112
|
+
upstreamPath: string,
|
|
113
|
+
init: RequestInit,
|
|
114
|
+
read: (response: Response) => Promise<T>,
|
|
115
|
+
signal?: AbortSignal,
|
|
116
|
+
): Promise<T> {
|
|
117
|
+
const controller = new AbortController();
|
|
118
|
+
let timedOut = false;
|
|
119
|
+
const timer = setTimeout(() => {
|
|
120
|
+
timedOut = true;
|
|
121
|
+
controller.abort();
|
|
122
|
+
}, config.timeoutMs);
|
|
123
|
+
const abort = () => controller.abort();
|
|
124
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
125
|
+
let release: (() => void) | undefined;
|
|
126
|
+
try {
|
|
127
|
+
if (signal?.aborted) controller.abort();
|
|
128
|
+
release = await acquireVoicePermit(config, controller.signal);
|
|
129
|
+
const response = await fetch(`${config.baseUrl}${upstreamPath}`, {
|
|
130
|
+
...init,
|
|
131
|
+
headers: { ...init.headers, authorization: `Bearer ${config.apiKey}` },
|
|
132
|
+
signal: controller.signal,
|
|
133
|
+
});
|
|
134
|
+
if (!response.ok) {
|
|
135
|
+
await discardErrorResponse(response);
|
|
136
|
+
if (response.status === 429) {
|
|
137
|
+
throw new VoiceServerError(VoiceErrorCodes.BUSY, 'Voice upstream is rate limited.', 429);
|
|
138
|
+
}
|
|
139
|
+
throw new VoiceServerError(
|
|
140
|
+
VoiceErrorCodes.UPSTREAM,
|
|
141
|
+
`Voice upstream failed (${response.status}).`,
|
|
142
|
+
502,
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
return await read(response);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (error instanceof VoiceServerError) throw error;
|
|
148
|
+
if (timedOut) {
|
|
149
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice upstream timed out.', 504);
|
|
150
|
+
}
|
|
151
|
+
if (signal?.aborted) {
|
|
152
|
+
throw new VoiceServerError(VoiceErrorCodes.TIMEOUT, 'Voice request was aborted.', 499);
|
|
153
|
+
}
|
|
154
|
+
throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Voice upstream unavailable.', 502);
|
|
155
|
+
} finally {
|
|
156
|
+
release?.();
|
|
157
|
+
clearTimeout(timer);
|
|
158
|
+
signal?.removeEventListener('abort', abort);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function rejectOversizedContentLength(request: Request, maxBytes: number): void {
|
|
163
|
+
const raw = request.headers.get('content-length');
|
|
164
|
+
if (!raw) return;
|
|
165
|
+
const length = Number(raw);
|
|
166
|
+
if (Number.isFinite(length) && length > maxBytes) {
|
|
167
|
+
throw new VoiceServerError(VoiceErrorCodes.AUDIO_TOO_LARGE, 'Audio request is too large.', 413);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function exceedsCodePoints(text: string, maximum: number): boolean {
|
|
172
|
+
let count = 0;
|
|
173
|
+
for (const _codePoint of text) {
|
|
174
|
+
count += 1;
|
|
175
|
+
if (count > maximum) return true;
|
|
176
|
+
}
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const AUDIO_MIME_BY_FORMAT: Record<string, string> = {
|
|
181
|
+
mp3: 'audio/mpeg',
|
|
182
|
+
wav: 'audio/wav',
|
|
183
|
+
opus: 'audio/ogg',
|
|
184
|
+
ogg: 'audio/ogg',
|
|
185
|
+
aac: 'audio/aac',
|
|
186
|
+
flac: 'audio/flac',
|
|
187
|
+
mp4: 'audio/mp4',
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
export interface ServerTranscriptionWord {
|
|
191
|
+
text: string;
|
|
192
|
+
startMs?: number;
|
|
193
|
+
endMs?: number;
|
|
194
|
+
speaker?: string;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export interface ServerTranscriptionSegment {
|
|
198
|
+
text: string;
|
|
199
|
+
startMs?: number;
|
|
200
|
+
endMs?: number;
|
|
201
|
+
speaker?: string;
|
|
202
|
+
words?: ServerTranscriptionWord[];
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export interface ServerTranscriptionResult {
|
|
206
|
+
text: string;
|
|
207
|
+
language?: string;
|
|
208
|
+
durationMs?: number;
|
|
209
|
+
segments?: ServerTranscriptionSegment[];
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function secondsToMilliseconds(value: unknown): number | undefined {
|
|
213
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0
|
|
214
|
+
? Math.round(value * 1000)
|
|
215
|
+
: undefined;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function parseProviderTranscription(value: unknown): ServerTranscriptionResult | undefined {
|
|
219
|
+
if (!value || typeof value !== 'object') return undefined;
|
|
220
|
+
const source = value as Record<string, unknown>;
|
|
221
|
+
if (typeof source.text !== 'string') return undefined;
|
|
222
|
+
const segments = Array.isArray(source.segments)
|
|
223
|
+
? source.segments.flatMap((segment) => {
|
|
224
|
+
if (!segment || typeof segment !== 'object') return [];
|
|
225
|
+
const item = segment as Record<string, unknown>;
|
|
226
|
+
if (typeof item.text !== 'string') return [];
|
|
227
|
+
const startMs = secondsToMilliseconds(item.start);
|
|
228
|
+
const endMs = secondsToMilliseconds(item.end);
|
|
229
|
+
const words = Array.isArray(item.words)
|
|
230
|
+
? item.words.flatMap((word) => {
|
|
231
|
+
if (!word || typeof word !== 'object') return [];
|
|
232
|
+
const entry = word as Record<string, unknown>;
|
|
233
|
+
const text = typeof entry.word === 'string'
|
|
234
|
+
? entry.word
|
|
235
|
+
: typeof entry.text === 'string' ? entry.text : undefined;
|
|
236
|
+
if (!text) return [];
|
|
237
|
+
const wordStartMs = secondsToMilliseconds(entry.start);
|
|
238
|
+
const wordEndMs = secondsToMilliseconds(entry.end);
|
|
239
|
+
return [{
|
|
240
|
+
text,
|
|
241
|
+
...(wordStartMs !== undefined ? { startMs: wordStartMs } : {}),
|
|
242
|
+
...(wordEndMs !== undefined ? { endMs: wordEndMs } : {}),
|
|
243
|
+
...(typeof entry.speaker === 'string' ? { speaker: entry.speaker } : {}),
|
|
244
|
+
}];
|
|
245
|
+
})
|
|
246
|
+
: undefined;
|
|
247
|
+
return [{
|
|
248
|
+
text: item.text,
|
|
249
|
+
...(startMs !== undefined ? { startMs } : {}),
|
|
250
|
+
...(endMs !== undefined ? { endMs } : {}),
|
|
251
|
+
...(typeof item.speaker === 'string' ? { speaker: item.speaker } : {}),
|
|
252
|
+
...(words ? { words } : {}),
|
|
253
|
+
}];
|
|
254
|
+
})
|
|
255
|
+
: undefined;
|
|
256
|
+
const durationMs = secondsToMilliseconds(source.duration);
|
|
257
|
+
return {
|
|
258
|
+
text: source.text,
|
|
259
|
+
...(typeof source.language === 'string' ? { language: source.language } : {}),
|
|
260
|
+
...(durationMs !== undefined ? { durationMs } : {}),
|
|
261
|
+
...(segments ? { segments } : {}),
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export async function transcribeDetailed(
|
|
266
|
+
request: Request,
|
|
267
|
+
config: VoiceConfig,
|
|
268
|
+
): Promise<ServerTranscriptionResult> {
|
|
269
|
+
const type = request.headers.get('content-type') ?? '';
|
|
270
|
+
if (!type.toLowerCase().startsWith('multipart/form-data')) {
|
|
271
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Expected multipart/form-data.');
|
|
272
|
+
}
|
|
273
|
+
// The framework still buffers multipart parsing; Content-Length rejects obvious oversize bodies first.
|
|
274
|
+
rejectOversizedContentLength(request, config.maxAudioBytes + 64 * 1024);
|
|
275
|
+
let form: FormData;
|
|
276
|
+
try {
|
|
277
|
+
form = await request.formData();
|
|
278
|
+
} catch {
|
|
279
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Malformed multipart request.');
|
|
280
|
+
}
|
|
281
|
+
const file = form.get('file');
|
|
282
|
+
if (!isBlobLike(file)) {
|
|
283
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Missing audio file.');
|
|
284
|
+
}
|
|
285
|
+
await validateAudio(file, config.maxAudioBytes);
|
|
286
|
+
const body = new FormData();
|
|
287
|
+
body.append('file', file as Blob, file.name || 'recording');
|
|
288
|
+
body.append('model', config.transcriptionModel);
|
|
289
|
+
const language = form.get('language');
|
|
290
|
+
const prompt = form.get('prompt');
|
|
291
|
+
if (language !== null
|
|
292
|
+
&& (typeof language !== 'string'
|
|
293
|
+
|| language.length > 32
|
|
294
|
+
|| !/^[A-Za-z]{2,8}(?:-[A-Za-z0-9]{1,8})*$/.test(language))) {
|
|
295
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid voice language.');
|
|
296
|
+
}
|
|
297
|
+
if (prompt !== null
|
|
298
|
+
&& (typeof prompt !== 'string' || [...prompt].length > 1_000)) {
|
|
299
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Voice prompt is too long.');
|
|
300
|
+
}
|
|
301
|
+
if (language) body.append('language', language);
|
|
302
|
+
if (prompt) body.append('prompt', prompt);
|
|
303
|
+
const responseFormat = form.get('response_format');
|
|
304
|
+
if (responseFormat !== null
|
|
305
|
+
&& responseFormat !== 'json'
|
|
306
|
+
&& responseFormat !== 'verbose_json') {
|
|
307
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_OPTION, 'Invalid response_format.');
|
|
308
|
+
}
|
|
309
|
+
body.append('response_format', responseFormat === 'verbose_json' ? 'verbose_json' : 'json');
|
|
310
|
+
return upstream(config, '/audio/transcriptions', { method: 'POST', body }, async (response) => {
|
|
311
|
+
const bytes = await readLimited(response, config.maxResponseBytes);
|
|
312
|
+
let json: unknown;
|
|
313
|
+
try {
|
|
314
|
+
json = JSON.parse(new TextDecoder().decode(bytes)) as unknown;
|
|
315
|
+
} catch {
|
|
316
|
+
// Mapped below as an invalid upstream response.
|
|
317
|
+
}
|
|
318
|
+
const result = parseProviderTranscription(json);
|
|
319
|
+
if (!result) {
|
|
320
|
+
throw new VoiceServerError(VoiceErrorCodes.UPSTREAM, 'Invalid transcription response.', 502);
|
|
321
|
+
}
|
|
322
|
+
return result;
|
|
323
|
+
}, request.signal);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
export async function transcribe(request: Request, config: VoiceConfig): Promise<string> {
|
|
327
|
+
return (await transcribeDetailed(request, config)).text;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
interface SynthesisRequest {
|
|
331
|
+
text: string;
|
|
332
|
+
voice: string;
|
|
333
|
+
format: string;
|
|
334
|
+
speed: number;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function readSynthesisRequest(
|
|
338
|
+
request: Request,
|
|
339
|
+
config: VoiceConfig,
|
|
340
|
+
): Promise<SynthesisRequest> {
|
|
341
|
+
if (!(request.headers.get('content-type') ?? '').toLowerCase().startsWith('application/json')) {
|
|
342
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Expected application/json.');
|
|
343
|
+
}
|
|
344
|
+
let input: unknown;
|
|
345
|
+
try {
|
|
346
|
+
input = await request.json();
|
|
347
|
+
} catch {
|
|
348
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Malformed JSON.');
|
|
349
|
+
}
|
|
350
|
+
if (!input || typeof input !== 'object') {
|
|
351
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'Invalid speech request.');
|
|
352
|
+
}
|
|
353
|
+
const values = input as Record<string, unknown>;
|
|
354
|
+
const text = values.text;
|
|
355
|
+
if (typeof text !== 'string' || !text.trim()) {
|
|
356
|
+
throw new VoiceServerError(VoiceErrorCodes.INVALID_REQUEST, 'text is required.');
|
|
357
|
+
}
|
|
358
|
+
if (exceedsCodePoints(text, config.maxTextCodePoints)) {
|
|
359
|
+
throw new VoiceServerError(VoiceErrorCodes.TEXT_TOO_LONG, 'Text is too long.');
|
|
360
|
+
}
|
|
361
|
+
const voice = values.voice ?? config.voices[0];
|
|
362
|
+
const format = values.format ?? config.formats[0];
|
|
363
|
+
const speed = values.speed ?? 1;
|
|
364
|
+
if (typeof voice !== 'string' || !config.voices.includes(voice)
|
|
365
|
+
|| typeof format !== 'string' || !config.formats.includes(format)
|
|
366
|
+
|| typeof speed !== 'number' || !config.speeds.includes(speed)) {
|
|
367
|
+
throw new VoiceServerError(
|
|
368
|
+
VoiceErrorCodes.INVALID_OPTION,
|
|
369
|
+
'Invalid voice, format, or speed.',
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
return { text, voice, format, speed };
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function synthesisUpstreamInit(config: VoiceConfig, input: SynthesisRequest): RequestInit {
|
|
376
|
+
return {
|
|
377
|
+
method: 'POST',
|
|
378
|
+
headers: { 'content-type': 'application/json' },
|
|
379
|
+
body: JSON.stringify({
|
|
380
|
+
model: config.speechModel,
|
|
381
|
+
input: input.text,
|
|
382
|
+
voice: input.voice,
|
|
383
|
+
response_format: input.format,
|
|
384
|
+
speed: input.speed,
|
|
385
|
+
}),
|
|
386
|
+
};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
export async function synthesize(request: Request, config: VoiceConfig): Promise<Response> {
|
|
390
|
+
const input = await readSynthesisRequest(request, config);
|
|
391
|
+
const result = await upstream(
|
|
392
|
+
config,
|
|
393
|
+
'/audio/speech',
|
|
394
|
+
synthesisUpstreamInit(config, input),
|
|
395
|
+
async (response) => {
|
|
396
|
+
const explicitType = response.headers.get('content-type');
|
|
397
|
+
if (explicitType && !explicitType.toLowerCase().startsWith('audio/')) {
|
|
398
|
+
await response.body?.cancel().catch(() => undefined);
|
|
399
|
+
throw new VoiceServerError(
|
|
400
|
+
VoiceErrorCodes.UPSTREAM,
|
|
401
|
+
'Voice upstream returned a non-audio response.',
|
|
402
|
+
502,
|
|
403
|
+
);
|
|
404
|
+
}
|
|
405
|
+
return {
|
|
406
|
+
bytes: await readLimited(response, config.maxResponseBytes),
|
|
407
|
+
mimeType: explicitType,
|
|
408
|
+
};
|
|
409
|
+
},
|
|
410
|
+
request.signal,
|
|
411
|
+
);
|
|
412
|
+
const responseBody = result.bytes.buffer.slice(
|
|
413
|
+
result.bytes.byteOffset,
|
|
414
|
+
result.bytes.byteOffset + result.bytes.byteLength,
|
|
415
|
+
) as ArrayBuffer;
|
|
416
|
+
return new Response(responseBody, {
|
|
417
|
+
status: 200,
|
|
418
|
+
headers: {
|
|
419
|
+
'content-type': result.mimeType || AUDIO_MIME_BY_FORMAT[input.format] || 'application/octet-stream',
|
|
420
|
+
'content-length': String(result.bytes.byteLength),
|
|
421
|
+
'cache-control': 'no-store',
|
|
422
|
+
'x-content-type-options': 'nosniff',
|
|
423
|
+
},
|
|
424
|
+
});
|
|
425
|
+
}
|