// PEP-108: dictation in the web — the browser records (MediaRecorder: webm/opus, Safari mp4) and // posts the audio here; Peppa forwards it to the same speech-to-text service as the Telegram bot // (PEPPA_TRANSCRIBE_URL, core/transcribe.ts) and returns the text. The page puts it into the // field, the user edits and sends. The recording is recognised in the user's interface language // (PEP-131). Logged-in users only; size cap and a per-user rate limit. import { transcribe, transcribeConfig, transcribeLanguage, TranscribeError } from "@peppa/core"; import { currentUser } from "@/lib/auth"; import { getLocale, getT } from "@/lib/i18n"; export const dynamic = "force-dynamic"; /** ~10 minutes of opus; the service itself takes up to 25 MB. */ const MAX_BYTES = 10 * 1024 * 1024; const PER_USER_PER_5MIN = 30; const g = globalThis as { __peppaTranscribeHits?: Map }; const hits = (g.__peppaTranscribeHits ??= new Map()); function limited(userId: number, now = Date.now()): boolean { const h = hits.get(userId); if (!h || now - h.at >= 5 * 60_000) { hits.set(userId, { at: now, n: 1 }); return false; } return ++h.n > PER_USER_PER_5MIN; } const json = (status: number, body: { text?: string; error?: string }) => Response.json(body, { status, headers: { "Cache-Control": "private, no-store" } }); export async function POST(req: Request) { const user = await currentUser(); const t = await getT(); if (!user) return json(401, { error: t("Нужно войти") }); const cfg = transcribeConfig(); if (!cfg) return json(503, { error: t("Распознавание речи не настроено — напишите текстом") }); if (Number(req.headers.get("content-length") ?? 0) > MAX_BYTES) return json(413, { error: t("Слишком длинная запись — запишите короче") }); if (limited(user.id)) return json(429, { error: t("Слишком много записей подряд — подождите пару минут") }); let file: FormDataEntryValue | null; try { file = (await req.formData()).get("file"); } catch { return json(400, { error: t("Запись не пришла") }); } if (!(file instanceof Blob) || !file.size) return json(400, { error: t("Запись пустая") }); if (file.size > MAX_BYTES) return json(413, { error: t("Слишком длинная запись — запишите короче") }); const type = file.type || "audio/webm"; const ext = type.includes("mp4") ? "m4a" : type.includes("ogg") ? "ogg" : type.includes("wav") ? "wav" : "webm"; try { const text = await transcribe(cfg, Buffer.from(await file.arrayBuffer()), `dictation.${ext}`, type, transcribeLanguage(cfg, await getLocale())); return json(200, { text }); } catch (e) { if (e instanceof TranscribeError) return json(502, { error: e.message }); throw e; } }