Files
khb_microservices/packages/khbuild_assistant_prep/src/slack/tts.ts
Yuri Yaryshev d8f3ddee37
All checks were successful
ci / test (push) Successful in 15s
ci / deploy (push) Successful in 1m5s
Озвучивание ответов (Google Chirp 3 HD): режим и голос на чат, миграция 007, загрузка аудио в Slack; docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 22:01:47 +03:00

105 lines
4.4 KiB
TypeScript

/** Голоса Google Cloud Text-to-Speech Chirp 3 HD (англоязычные; полное имя - `en-US-Chirp3-HD-<голос>`). */
export const CHIRP3_VOICES = [
"Achernar", "Achird", "Algenib", "Algieba", "Alnilam", "Aoede", "Autonoe", "Callirrhoe", "Charon", "Despina",
"Enceladus", "Erinome", "Fenrir", "Gacrux", "Iapetus", "Kore", "Laomedeia", "Leda", "Orus", "Pulcherrima",
"Puck", "Rasalgethi", "Sadachbia", "Sadaltager", "Schedar", "Sulafat", "Umbriel", "Vindemiatrix", "Zephyr", "Zubenelgenubi",
] as const;
export type ReplyMode = "text" | "both" | "audio";
export function isReplyMode(v: unknown): v is ReplyMode {
return v === "text" || v === "both" || v === "audio";
}
/** Приводит имя голоса (`aoede`, `Aoede`, `en-US-Chirp3-HD-Aoede`) к короткому виду или возвращает null. */
export function normalizeVoice(v: string | null | undefined): string | null {
if (!v) return null;
const short = v.trim().replace(/^en-US-Chirp3-HD-/i, "");
return CHIRP3_VOICES.find((x) => x.toLowerCase() === short.toLowerCase()) ?? null;
}
/** Текст ответа для озвучивания: без Markdown, ссылок и эмодзи-оформления. */
export function speechText(md: string): string {
return md
.replace(/```[\s\S]*?```/g, " ")
.replace(/<(https?:[^|>]+)\|([^>]+)>/g, "$2") // ссылка Slack <url|текст>
.replace(/<https?:[^>]+>/g, " ")
.replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
.replace(/https?:\/\/\S+/g, " ")
.replace(/[*_`~>#]+/g, "")
.replace(/^\s*[-•]\s+/gm, "")
.replace(/\p{Extended_Pictographic}/gu, "")
.replace(/[ \t]+/g, " ")
.replace(/\n{2,}/g, "\n")
.trim();
}
/** Делит текст на части до maxBytes (лимит API - 5000 байт на запрос) по границам предложений/строк. */
export function splitForTts(text: string, maxBytes = 4000): string[] {
const parts: string[] = [];
let cur = "";
const flush = () => {
if (cur.trim()) parts.push(cur.trim());
cur = "";
};
for (const piece of text.split(/(?<=[.!?\n])\s+/)) {
if (Buffer.byteLength(piece) > maxBytes) {
flush();
let rest = piece;
while (Buffer.byteLength(rest) > maxBytes) {
let cut = Math.min(rest.length, maxBytes);
while (Buffer.byteLength(rest.slice(0, cut)) > maxBytes) cut--;
const sp = rest.lastIndexOf(" ", cut);
cut = sp > cut / 2 ? sp : cut;
parts.push(rest.slice(0, cut).trim());
rest = rest.slice(cut);
}
cur = rest;
continue;
}
if (Buffer.byteLength(cur) + Buffer.byteLength(piece) + 1 > maxBytes) flush();
cur += (cur ? " " : "") + piece;
}
flush();
return parts;
}
export interface Tts {
/** Озвучивает текст голосом (короткое имя Chirp 3 HD); возвращает MP3. */
synthesize(text: string, voice: string): Promise<Buffer>;
}
export interface TtsConfig {
apiKey: string;
languageCode: string;
speakingRate?: number;
}
/** Google Cloud Text-to-Speech (REST, ключ API): `texttospeech.googleapis.com/v1/text:synthesize`. */
export function createGoogleTts(cfg: TtsConfig, fetchFn: typeof fetch = fetch): Tts {
return {
async synthesize(text, voice) {
const name = normalizeVoice(voice);
if (!name) throw new Error(`неизвестный голос Chirp 3 HD: ${voice}`);
const chunks = splitForTts(speechText(text));
if (!chunks.length) throw new Error("нечего озвучивать");
const out: Buffer[] = [];
for (const chunk of chunks) {
const res = await fetchFn(`https://texttospeech.googleapis.com/v1/text:synthesize?key=${encodeURIComponent(cfg.apiKey)}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
input: { text: chunk },
voice: { languageCode: cfg.languageCode, name: `${cfg.languageCode}-Chirp3-HD-${name}` },
audioConfig: { audioEncoding: "MP3", ...(cfg.speakingRate ? { speakingRate: cfg.speakingRate } : {}) },
}),
});
const j = (await res.json()) as { audioContent?: string; error?: { message?: string } };
if (!res.ok || !j.audioContent) throw new Error(`Google TTS: ${j.error?.message ?? `HTTP ${res.status}`}`);
out.push(Buffer.from(j.audioContent, "base64"));
}
return Buffer.concat(out);
},
};
}