59 lines
2.7 KiB
TypeScript
59 lines
2.7 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. Peppa's own is
|
|
// infra/whisper/server.py (faster-whisper, 127.0.0.1:8178). The web dictation route
|
|
// (apps/web/app/api/transcribe) uses it too. Tests use
|
|
// mock-transcribe (packages/testkit).
|
|
import { m as tr } from "@peppa/shared/i18n";
|
|
|
|
export interface TranscribeConfig {
|
|
url: string;
|
|
key: string | null;
|
|
model: string;
|
|
language: string | null;
|
|
/** How long to wait for the text: a local model on CPU (PEP-108) is slower than a cloud API. */
|
|
timeoutMs: number;
|
|
}
|
|
|
|
/** 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"),
|
|
timeoutMs: (Number(env.PEPPA_TRANSCRIBE_TIMEOUT_SEC) > 0 ? Number(env.PEPPA_TRANSCRIBE_TIMEOUT_SEC) : 300) * 1000,
|
|
};
|
|
}
|
|
|
|
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(cfg.timeoutMs),
|
|
});
|
|
} catch (e) {
|
|
throw new TranscribeError(tr("сервис расшифровки недоступен: {error}", { error: (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(tr("расшифровка не удалась: {status}", { status: `${res.status}${msg ? ` ${msg}` : ""}` }));
|
|
}
|
|
return (body.text ?? "").trim();
|
|
}
|