Озвучивание ответов (Google Chirp 3 HD): режим и голос на чат, миграция 007, загрузка аудио в Slack; docs
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,8 @@ export interface SlackApi {
|
||||
postMessage(channel: string, text: string, threadTs?: string): Promise<boolean>;
|
||||
fileInfo(fileId: string): Promise<SlackFile | null>;
|
||||
download(file: SlackFile, toPath: string): Promise<number>;
|
||||
/** Загружает файл в канал (нужен scope files:write). */
|
||||
uploadFile?(channel: string, filename: string, data: Buffer, title?: string): Promise<void>;
|
||||
}
|
||||
|
||||
/** Web API Slack под токеном бота (отправка сообщений и скачивание вложений). */
|
||||
@@ -38,6 +40,19 @@ export function createSlackApi(botToken: string, fetchFn: typeof fetch = fetch):
|
||||
if (!j.ok || !f || typeof f.url_private_download !== "string") return null;
|
||||
return { id: String(f.id), name: String(f.name ?? f.id), mimetype: String(f.mimetype ?? ""), size: Number(f.size ?? 0), urlPrivateDownload: f.url_private_download };
|
||||
},
|
||||
async uploadFile(channel, filename, data, title) {
|
||||
const form = new URLSearchParams({ filename, length: String(data.length) });
|
||||
const start = (await (await fetchFn("https://slack.com/api/files.getUploadURLExternal", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/x-www-form-urlencoded", authorization: `Bearer ${botToken}` },
|
||||
body: form,
|
||||
})).json()) as { ok?: boolean; error?: string; upload_url?: string; file_id?: string };
|
||||
if (!start.ok || !start.upload_url || !start.file_id) throw new Error(`Slack files.getUploadURLExternal: ${start.error ?? "нет upload_url"}`);
|
||||
const up = await fetchFn(start.upload_url, { method: "POST", body: new Uint8Array(data) });
|
||||
if (!up.ok) throw new Error(`Slack upload: HTTP ${up.status}`);
|
||||
const done = await call("files.completeUploadExternal", { files: [{ id: start.file_id, title: title ?? filename }], channel_id: channel });
|
||||
if (!done.ok) throw new Error(`Slack files.completeUploadExternal: ${done.error}`);
|
||||
},
|
||||
async download(file, toPath) {
|
||||
const res = await fetchFn(file.urlPrivateDownload, { headers: { authorization: `Bearer ${botToken}` } });
|
||||
if (!res.ok) throw new Error(`скачивание ${file.name}: HTTP ${res.status}`);
|
||||
|
||||
@@ -6,12 +6,17 @@ import { loadPrompt } from "../agents/prompts.js";
|
||||
import { saveProblems } from "../agents/step2.js";
|
||||
import type { DriveSync } from "./drive.js";
|
||||
import type { SlackApi } from "./api.js";
|
||||
import { normalizeVoice, speechText, type ReplyMode, type Tts } from "./tts.js";
|
||||
|
||||
export interface ManagerInfo {
|
||||
personId: string;
|
||||
name: string;
|
||||
slackUserId: string | null;
|
||||
slackChannelId: string | null;
|
||||
/** Режим ответов в чате: text (по умолчанию) / both / audio. */
|
||||
replyMode?: ReplyMode;
|
||||
/** Голос Chirp 3 HD для чата; null - по умолчанию. */
|
||||
ttsVoice?: string | null;
|
||||
}
|
||||
|
||||
export interface IncomingMessage {
|
||||
@@ -25,7 +30,10 @@ export interface IncomingMessage {
|
||||
|
||||
export interface ChatDeps {
|
||||
ctx: AgentContext;
|
||||
slack: Pick<SlackApi, "postMessage" | "fileInfo" | "download">;
|
||||
slack: Pick<SlackApi, "postMessage" | "fileInfo" | "download" | "uploadFile">;
|
||||
/** Синтез речи; без него ответы всегда текстовые. */
|
||||
tts?: Tts;
|
||||
defaultVoice?: string;
|
||||
drive?: DriveSync;
|
||||
timezone: string;
|
||||
now?: () => Date;
|
||||
@@ -36,6 +44,8 @@ export interface ChatDeps {
|
||||
export interface ChatResult {
|
||||
reply: string | null;
|
||||
published: boolean;
|
||||
/** Аудиоответ отправлен. */
|
||||
audioSent?: boolean;
|
||||
attachments: { name: string; path: string; mimetype: string; size: number; link?: string }[];
|
||||
}
|
||||
|
||||
@@ -164,7 +174,8 @@ export async function handleManagerMessages(
|
||||
const replyRaw = out.sections.get("ответ менеджеру")!;
|
||||
const reply = /^\(без ответа\)\.?$/i.test(replyRaw) ? null : replyRaw;
|
||||
let published = false;
|
||||
if (reply && channel && !deps.dryPublish) published = await deps.slack.postMessage(channel, reply);
|
||||
let audioSent = false;
|
||||
if (reply && channel && !deps.dryPublish) ({ published, audioSent } = await publishReply(deps, manager, channel, reply));
|
||||
if (reply && opts.systemEvent) {
|
||||
// напоминание ассистента по событию - в историю напоминаний (вход 7)
|
||||
await ctx.pool.query(
|
||||
@@ -176,5 +187,25 @@ export async function handleManagerMessages(
|
||||
|
||||
// 6. транскрипты и итоговые файлы -> Drive
|
||||
if (deps.drive && attachments.length) await deps.drive.upload(mediaDir, sub).catch((e) => ctx.log.warn({ err: String(e) }, "повторная выгрузка в Drive не удалась"));
|
||||
return { reply, published, attachments };
|
||||
return { reply, published, audioSent, attachments };
|
||||
}
|
||||
|
||||
/** Публикует ответ по настройке чата: текст / текст и аудио / только аудио. Любой сбой аудио - ответ уходит текстом, ИТ видит проблему в логе. */
|
||||
export async function publishReply(deps: ChatDeps, manager: ManagerInfo, channel: string, reply: string): Promise<{ published: boolean; audioSent: boolean }> {
|
||||
const mode = manager.replyMode ?? "text";
|
||||
const voice = normalizeVoice(manager.ttsVoice) ?? normalizeVoice(deps.defaultVoice) ?? "Aoede";
|
||||
let audioSent = false;
|
||||
if (mode !== "text" && deps.tts && deps.slack.uploadFile && speechText(reply)) {
|
||||
try {
|
||||
const mp3 = await deps.tts.synthesize(reply, voice);
|
||||
await deps.slack.uploadFile(channel, "assistant-reply.mp3", mp3, "Voice reply");
|
||||
audioSent = true;
|
||||
} catch (e) {
|
||||
deps.ctx.log.warn({ manager: manager.personId, err: String(e) }, "аудиоответ не отправлен, отправляю текстом");
|
||||
await deps.ctx.pool.query("insert into agent_problem_log (manager_person_id, step, severity, body) values ($1,'step4','log',$2)", [manager.personId, `Аудиоответ (Chirp 3 HD, ${voice}) не отправлен: ${String(e).slice(0, 400)}`]);
|
||||
}
|
||||
}
|
||||
const needText = mode === "text" || mode === "both" || !audioSent;
|
||||
const published = needText ? await deps.slack.postMessage(channel, reply) : false;
|
||||
return { published: published || audioSent, audioSent };
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Pool } from "khb_common";
|
||||
import { isReplyMode } from "./tts.js";
|
||||
import { handleManagerMessages, type ChatDeps, type IncomingMessage, type ManagerInfo } from "./chat.js";
|
||||
|
||||
interface Pending {
|
||||
@@ -7,6 +8,17 @@ interface Pending {
|
||||
timer: NodeJS.Timeout;
|
||||
}
|
||||
|
||||
export function rowToManager(r: Record<string, unknown>): ManagerInfo {
|
||||
return {
|
||||
personId: String(r.person_id),
|
||||
name: String(r.display_name),
|
||||
slackUserId: (r.slack_user_id as string | null) ?? null,
|
||||
slackChannelId: (r.slack_channel_id as string | null) ?? null,
|
||||
replyMode: isReplyMode(r.reply_mode) ? r.reply_mode : "text",
|
||||
ttsVoice: (r.tts_voice as string | null) ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
const ACCEPTED_SUBTYPES = new Set([undefined, "file_share", "thread_broadcast"]);
|
||||
|
||||
/** Приём сообщений Slack: фильтр, журнал (защита от дублей), накопление сообщений менеджера (debounce) и запуск шага 4. */
|
||||
@@ -27,13 +39,13 @@ export class SlackIntake {
|
||||
|
||||
async findManagerBySlackUser(slackUserId: string): Promise<ManagerInfo | null> {
|
||||
const { rows } = await this.pool.query(
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
|
||||
from construction_manager cm join person p on p.id = cm.person_id
|
||||
where cm.slack_user_id = $1 and cm.is_active and p.is_active`,
|
||||
[slackUserId],
|
||||
);
|
||||
const r = rows[0];
|
||||
return r ? { personId: r.person_id, name: r.display_name, slackUserId: r.slack_user_id, slackChannelId: r.slack_channel_id } : null;
|
||||
return r ? rowToManager(r) : null;
|
||||
}
|
||||
|
||||
private chain: Promise<void> = Promise.resolve();
|
||||
@@ -60,13 +72,13 @@ export class SlackIntake {
|
||||
/** Менеджер чата (по slack_channel_id или единственный активный менеджер для каналов из настроек). */
|
||||
async findManagerByChannel(channel: string): Promise<ManagerInfo | null> {
|
||||
const { rows } = await this.pool.query(
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id
|
||||
`select cm.person_id, p.display_name, cm.slack_user_id, cm.slack_channel_id, cm.reply_mode, cm.tts_voice
|
||||
from construction_manager cm join person p on p.id = cm.person_id
|
||||
where cm.slack_channel_id = $1 and cm.is_active and p.is_active order by cm.person_id limit 1`,
|
||||
[channel],
|
||||
);
|
||||
const r = rows[0];
|
||||
return r ? { personId: r.person_id, name: r.display_name, slackUserId: r.slack_user_id, slackChannelId: r.slack_channel_id } : null;
|
||||
return r ? rowToManager(r) : null;
|
||||
}
|
||||
|
||||
/** Файл из папки приёма на Drive = сообщение менеджера в чате (текстовые файлы - текст сообщения). */
|
||||
|
||||
104
packages/khbuild_assistant_prep/src/slack/tts.ts
Normal file
104
packages/khbuild_assistant_prep/src/slack/tts.ts
Normal file
@@ -0,0 +1,104 @@
|
||||
/** Голоса 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);
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user