peppa/apps/bot/src/transcribe.ts
Асель db822a570c PEP-45: stories from a Telegram message (text or voice); docs; archive PEP-44/45/46 changes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 06:07:18 +05:00

53 lines
2.2 KiB
TypeScript

// Speech to text for voice notes (PEP-45): any OpenAI-compatible audio API —
// POST $PEPPA_TRANSCRIBE_URL/audio/transcriptions (multipart: file, model, language,
// response_format=json) with "Authorization: Bearer $PEPPA_TRANSCRIBE_KEY" → {"text": "…"}.
// OpenAI (https://api.openai.com/v1, whisper-1), Groq (https://api.groq.com/openai/v1,
// whisper-large-v3), a local faster-whisper/speaches server — all speak this. Tests use
// mock-transcribe (packages/testkit).
export interface TranscribeConfig {
url: string;
key: string | null;
model: string;
language: string | null;
}
/** From env; null when voice is not set up (the bot asks for text then). */
export function transcribeConfig(env: NodeJS.ProcessEnv = process.env): TranscribeConfig | null {
const url = env.PEPPA_TRANSCRIBE_URL?.trim();
if (!url) return null;
return {
url: url.replace(/\/$/, ""),
key: env.PEPPA_TRANSCRIBE_KEY?.trim() || null,
model: env.PEPPA_TRANSCRIBE_MODEL?.trim() || "whisper-1",
language: env.PEPPA_TRANSCRIBE_LANG === "" ? null : (env.PEPPA_TRANSCRIBE_LANG?.trim() || "ru"),
};
}
export class TranscribeError extends Error {}
export async function transcribe(cfg: TranscribeConfig, audio: Buffer, filename = "voice.ogg", mime = "audio/ogg"): Promise<string> {
const form = new FormData();
form.set("file", new Blob([new Uint8Array(audio)], { type: mime }), filename);
form.set("model", cfg.model);
form.set("response_format", "json");
if (cfg.language) form.set("language", cfg.language);
let res: Response;
try {
res = await fetch(`${cfg.url}/audio/transcriptions`, {
method: "POST",
headers: cfg.key ? { Authorization: `Bearer ${cfg.key}` } : {},
body: form,
signal: AbortSignal.timeout(120_000),
});
} catch (e) {
throw new TranscribeError(`сервис расшифровки недоступен: ${(e as Error).message}`);
}
const body = (await res.json().catch(() => ({}))) as { text?: string; error?: { message?: string } | string };
if (!res.ok) {
const msg = typeof body.error === "string" ? body.error : body.error?.message;
throw new TranscribeError(`расшифровка не удалась: ${res.status}${msg ? ` ${msg}` : ""}`);
}
return (body.text ?? "").trim();
}