-
-
Notifications
You must be signed in to change notification settings - Fork 8.5k
Expand file tree
/
Copy pathawsPollyTts.ts
More file actions
161 lines (143 loc) · 5.1 KB
/
Copy pathawsPollyTts.ts
File metadata and controls
161 lines (143 loc) · 5.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
/**
* AWS Polly TTS handler.
*
* Extracted out of `open-sse/handlers/audioSpeech.ts` (frozen at its
* file-size ratchet baseline — config/quality/file-size-baseline.json).
* Pure provider adapter, no behavior change vs. the original inline implementation.
*
* POST /v1/speech signed with AWS SigV4. The configured apiKey stores AWS
* Secret Access Key; providerSpecificData.accessKeyId stores AWS Access Key
* ID, with optional region/baseUrl/defaultVoice/sessionToken.
*/
import { stripTrailingSlashes } from "../utils/urlSanitize.ts";
import { signAwsRequest } from "../utils/awsSigV4.ts";
import { errorResponse } from "../utils/error.ts";
import { audioStreamResponse, upstreamErrorResponse } from "../utils/audioResponse.ts";
function getStringValue(value: unknown): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function getAwsPollyProviderData(credentials) {
return credentials?.providerSpecificData &&
typeof credentials.providerSpecificData === "object" &&
!Array.isArray(credentials.providerSpecificData)
? credentials.providerSpecificData
: {};
}
function resolveAwsPollyRegion(providerSpecificData) {
return (
getStringValue(providerSpecificData.region) ||
getStringValue(providerSpecificData.awsRegion) ||
process.env.AWS_REGION ||
process.env.AWS_DEFAULT_REGION ||
"us-east-1"
);
}
function resolveAwsPollyBaseUrl(providerSpecificData, region) {
const configuredBaseUrl = getStringValue(providerSpecificData.baseUrl);
const baseUrl = configuredBaseUrl || `https://polly.${region}.amazonaws.com`;
return stripTrailingSlashes(baseUrl.replace(/\/v1\/speech\/?$/i, ""));
}
function normalizeAwsPollyEngine(modelId) {
const engine = getStringValue(modelId) || "standard";
return ["standard", "neural", "long-form", "generative"].includes(engine) ? engine : "standard";
}
function normalizeAwsPollyOutputFormat(responseFormat) {
const format = getStringValue(responseFormat)?.toLowerCase();
switch (format) {
case "pcm":
case "wav":
return "pcm";
case "opus":
case "ogg_opus":
return "ogg_opus";
case "ogg":
case "ogg_vorbis":
return "ogg_vorbis";
case "json":
return "json";
case "mp3":
default:
return "mp3";
}
}
function normalizeAwsPollyTextType(body) {
const explicitTextType = getStringValue(body.text_type || body.textType)?.toLowerCase();
if (explicitTextType === "ssml") return "ssml";
if (explicitTextType === "text") return "text";
const input = getStringValue(body.input) || "";
return input.trim().startsWith("<speak") ? "ssml" : "text";
}
function getAwsPollySampleRate(responseFormat, sampleRate) {
const explicit = getStringValue(sampleRate || null);
if (explicit) return explicit;
const outputFormat = normalizeAwsPollyOutputFormat(responseFormat);
if (outputFormat === "ogg_opus") return "48000";
if (outputFormat === "pcm") return "16000";
return undefined;
}
export async function handleAwsPollySpeech(
providerConfig,
body,
modelId,
token,
credentials
): Promise<Response> {
const providerSpecificData = getAwsPollyProviderData(credentials);
const accessKeyId =
getStringValue(providerSpecificData.accessKeyId) ||
getStringValue(providerSpecificData.awsAccessKeyId);
const secretAccessKey = getStringValue(token);
if (!accessKeyId) {
return errorResponse(400, "AWS Polly requires providerSpecificData.accessKeyId");
}
if (!secretAccessKey) {
return errorResponse(401, "No AWS Secret Access Key for AWS Polly");
}
const region = resolveAwsPollyRegion(providerSpecificData);
const baseUrl = resolveAwsPollyBaseUrl(providerSpecificData, region);
const url = `${baseUrl}/v1/speech`;
const outputFormat = normalizeAwsPollyOutputFormat(body.response_format);
const sampleRate = getAwsPollySampleRate(
body.response_format,
body.sample_rate || body.sampleRate
);
const requestBody = {
Engine: normalizeAwsPollyEngine(modelId),
OutputFormat: outputFormat,
Text: body.input,
TextType: normalizeAwsPollyTextType(body),
VoiceId:
getStringValue(body.voice) || getStringValue(providerSpecificData.defaultVoice) || "Joanna",
...(getStringValue(body.language_code || body.languageCode)
? { LanguageCode: getStringValue(body.language_code || body.languageCode) }
: {}),
...(sampleRate ? { SampleRate: sampleRate } : {}),
};
const serializedBody = JSON.stringify(requestBody);
const signedHeaders = signAwsRequest({
method: "POST",
url,
region,
service: "polly",
headers: {
"content-type": "application/json",
},
body: serializedBody,
credentials: {
accessKeyId,
secretAccessKey,
sessionToken:
getStringValue(providerSpecificData.sessionToken) ||
getStringValue(providerSpecificData.awsSessionToken),
},
});
const res = await fetch(url, {
method: "POST",
headers: signedHeaders,
body: serializedBody,
});
if (!res.ok) {
return upstreamErrorResponse(res, await res.text());
}
return audioStreamResponse(res, outputFormat === "pcm" ? "audio/pcm" : "audio/mpeg");
}