Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Hear speech through Fish Audio: POST /api/tts/transcribe

aivsomkarfb4747ff11a2
diff --git a/server/routes/tts.test.ts b/server/routes/tts.test.ts
index 8c7af9f8ab..8df2cbe7b9 100644
--- a/server/routes/tts.test.ts
+++ b/server/routes/tts.test.ts
@@ -1,15 +1,16 @@
-import { describe, expect, it } from "vitest";
+import { Readable } from "node:stream";
+import { afterEach, describe, expect, it, vi } from "vitest";
import type { AppConfig } from "../config.ts";
import { addHeldSecretScrubber } from "../redact.ts";
import { VOICE_FIRST_BLOCK_MAX_CHARS } from "../tts/speech-text.ts";
import { PASS } from "./table.ts";
-import { createTtsRoutes } from "./tts.ts";
+import { createTtsRoutes, TRANSCRIBE_MAX_BYTES } from "./tts.ts";
-async function call(method: string, path: string, body: unknown = {}, cfg = {} as AppConfig) {
+async function call(method: string, path: string, body: unknown = {}, cfg = {} as AppConfig, req = {} as never) {
const answers: Array<[number, unknown]> = [];
const out = await createTtsRoutes({ config: () => cfg })({
- req: {} as never, res: {} as never, url: new URL(`http://x${path}`), path: new URL(`http://x${path}`).pathname, method,
+ req, res: {} as never, url: new URL(`http://x${path}`), path: new URL(`http://x${path}`).pathname, method,
auth: { kind: "loopback", scopes: ["admin", "client"] },
json: ((_res: unknown, status: number, value: unknown) => { answers.push([status, value]); }) as never, readBody: (async () => body) as never,
});
@@ -49,3 +50,39 @@ describe("voice routes", () => {
expect((answers[0]![1] as { voices: unknown[] }).voices).toEqual([]);
});
});
+
+describe("transcribe route", () => {
+ afterEach(() => vi.unstubAllGlobals());
+ const withKey = { tts: { fishKey: "fish-key" } } as AppConfig;
+ const upload = (bytes: Buffer, type = "audio/wav") =>
+ Object.assign(Readable.from([bytes]), { headers: { "content-type": type, "content-length": String(bytes.byteLength) } }) as never;
+
+ it("refuses anything but WAV audio", async () => {
+ const { answers } = await call("POST", "/api/tts/transcribe", {}, withKey, upload(Buffer.from("x"), "application/json"));
+ expect(answers).toEqual([[400, { error: "content-type must be audio/wav" }]]);
+ });
+
+ it("asks for a Fish key when none is saved", async () => {
+ const { answers } = await call("POST", "/api/tts/transcribe", {}, {} as AppConfig, upload(Buffer.from("x")));
+ expect(answers[0]![0]).toBe(409);
+ expect((answers[0]![1] as { error: string }).error).toContain("Fish Audio key");
+ });
+
+ it("refuses audio over the cap", async () => {
+ const { answers } = await call("POST", "/api/tts/transcribe", {}, withKey, upload(Buffer.alloc(TRANSCRIBE_MAX_BYTES + 1)));
+ expect(answers[0]![0]).toBe(413);
+ });
+
+ it("returns the text Fish heard", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ text: "hi bot" }), { status: 200 })));
+ const { answers } = await call("POST", "/api/tts/transcribe", {}, withKey, upload(Buffer.from("RIFF")));
+ expect(answers).toEqual([[200, { text: "hi bot" }]]);
+ });
+
+ it("answers 502 with Fish's message when Fish fails", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ message: "nope" }), { status: 401 })));
+ const { answers } = await call("POST", "/api/tts/transcribe", {}, withKey, upload(Buffer.from("RIFF")));
+ expect(answers[0]![0]).toBe(502);
+ expect((answers[0]![1] as { error: string }).error).toContain("rejected that API key");
+ });
+});
diff --git a/server/routes/tts.ts b/server/routes/tts.ts
index 060b281212..1ebf8d5457 100644
--- a/server/routes/tts.ts
+++ b/server/routes/tts.ts
@@ -1,11 +1,15 @@
// The voice routes: whether a voice is ready, the provider's voices (searched, or one pasted by ID or link), adding an
-// ElevenLabs Voice Library voice to My Voices, and speaking a line. Scopes are keyed by path in server/request-auth.ts.
+// ElevenLabs Voice Library voice to My Voices, speaking a line, and hearing speech. Scopes are keyed by path in server/request-auth.ts.
import type { AppConfig } from "../config.ts";
import { redactSecretsInText } from "../redact.ts";
+import * as fish from "../tts/fish.ts";
import * as tts from "../tts/index.ts";
import { toUtterances, VOICE_FIRST_BLOCK_MAX_CHARS } from "../tts/speech-text.ts";
import { PASS, type RouteHandler } from "./table.ts";
+/** About six minutes of 16 kHz mono 16-bit PCM. */
+export const TRANSCRIBE_MAX_BYTES = 12 * 1024 * 1024;
+
export interface TtsRouteDeps {
config(): AppConfig;
}
@@ -68,6 +72,51 @@ export function createTtsRoutes(deps: TtsRouteDeps): RouteHandler {
return json(res, 502, { error: e instanceof Error ? e.message : String(e) });
}
}
+ if (method === "POST" && path === "/api/tts/transcribe") {
+ const rawType = req.headers["content-type"];
+ const mime = (Array.isArray(rawType) ? rawType[0] : rawType)?.split(";")[0]?.trim().toLowerCase();
+ if (mime !== "audio/wav") {
+ req.resume();
+ return json(res, 400, { error: "content-type must be audio/wav" });
+ }
+ const key = cfg.tts?.fishKey;
+ if (!key) {
+ req.resume();
+ return json(res, 409, { error: "Add a Fish Audio key in Settings → API keys to talk to your bots here." });
+ }
+ const declared = Number(req.headers["content-length"] ?? 0);
+ if (declared > TRANSCRIBE_MAX_BYTES) {
+ req.resume();
+ return json(res, 413, { error: `audio exceeds ${TRANSCRIBE_MAX_BYTES} bytes` });
+ }
+ const audio = await new Promise<Buffer | null>((resolve, reject) => {
+ const chunks: Buffer[] = [];
+ let received = 0;
+ let settled = false;
+ // Past the cap the listeners stay attached and drop the rest, so the request drains.
+ req.on("data", (chunk: Buffer) => {
+ if (settled) return;
+ received += chunk.byteLength;
+ if (received > TRANSCRIBE_MAX_BYTES) {
+ settled = true;
+ return resolve(null);
+ }
+ chunks.push(chunk);
+ });
+ req.on("end", () => {
+ if (settled) return;
+ settled = true;
+ resolve(Buffer.concat(chunks));
+ });
+ req.on("error", reject);
+ });
+ if (!audio) return json(res, 413, { error: `audio exceeds ${TRANSCRIBE_MAX_BYTES} bytes` });
+ try {
+ return json(res, 200, { text: await fish.transcribe(audio, mime, key) });
+ } catch (e) {
+ return json(res, 502, { error: e instanceof Error ? e.message : String(e) });
+ }
+ }
return PASS;
};
}
diff --git a/server/tts/fish.test.ts b/server/tts/fish.test.ts
new file mode 100644
index 0000000000..d4aad9c009
--- /dev/null
+++ b/server/tts/fish.test.ts
@@ -0,0 +1,46 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { transcribe } from "./fish.ts";
+
+afterEach(() => vi.unstubAllGlobals());
+
+function stubFetch(status: number, body: unknown) {
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify(body), { status }));
+ vi.stubGlobal("fetch", fetchMock);
+ return fetchMock;
+}
+
+describe("Fish Audio transcribe", () => {
+ it("sends the clip with the pro model and returns the trimmed text", async () => {
+ const fetchMock = stubFetch(200, { text: " hello there ", duration: 1.2 });
+ expect(await transcribe(new Uint8Array([1, 2, 3]), "audio/wav", "fish-key")).toBe("hello there");
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
+ expect(url).toMatch(/\/v1\/asr$/);
+ expect(init.method).toBe("POST");
+ expect(init.headers).toEqual({ authorization: "Bearer fish-key", model: "transcribe-1-pro" });
+ const form = init.body as FormData;
+ expect(form.get("ignore_timestamps")).toBe("true");
+ expect(form.get("diarize")).toBe("false");
+ expect(form.get("tag_audio_events")).toBe("false");
+ const audio = form.get("audio") as File;
+ expect(audio.name).toBe("speech.wav");
+ expect(audio.size).toBe(3);
+ });
+
+ it("returns empty text when Fish heard nothing", async () => {
+ stubFetch(200, {});
+ expect(await transcribe(new Uint8Array(4), "audio/wav", "k")).toBe("");
+ });
+
+ it("explains a rejected key and an empty balance", async () => {
+ stubFetch(401, { message: "bad" });
+ await expect(transcribe(new Uint8Array(4), "audio/wav", "k")).rejects.toThrow("rejected that API key");
+ stubFetch(402, { message: "Out of credit" });
+ await expect(transcribe(new Uint8Array(4), "audio/wav", "k")).rejects.toThrow("Out of credit");
+ });
+
+ it("says Fish was unreachable when the request throws", async () => {
+ vi.stubGlobal("fetch", vi.fn(async () => { throw new TypeError("fetch failed"); }));
+ await expect(transcribe(new Uint8Array(4), "audio/wav", "k")).rejects.toThrow("Couldn't reach Fish Audio to hear you");
+ });
+});
diff --git a/server/tts/fish.ts b/server/tts/fish.ts
index d17fc86f75..7956c8547b 100644
--- a/server/tts/fish.ts
+++ b/server/tts/fish.ts
@@ -204,3 +204,26 @@ export async function synthesize(
if (!res.ok) throw new Error(errorMessage(res.status, "speaking", await safeBody(res)));
return { bytes: new Uint8Array(await res.arrayBuffer()), mime: "audio/mpeg" };
}
+
+export async function transcribe(audio: Uint8Array, mime: string, key: string): Promise<string> {
+ const form = new FormData();
+ form.append("audio", new Blob([audio as Uint8Array<ArrayBuffer>], { type: mime }), "speech.wav");
+ form.append("ignore_timestamps", "true");
+ form.append("diarize", "false");
+ form.append("tag_audio_events", "false");
+ let res: Response;
+ try {
+ res = await fetch(`${API}/v1/asr`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${key}`, model: "transcribe-1-pro" },
+ body: form,
+ signal: AbortSignal.timeout(60_000),
+ });
+ } catch {
+ throw new Error("Couldn't reach Fish Audio to hear you — check your connection.");
+ }
+ const body = await safeBody(res);
+ if (!res.ok) throw new Error(errorMessage(res.status, "hearing you", body));
+ const text = body && typeof body === "object" ? (body as Record<string, unknown>).text : undefined;
+ return typeof text === "string" ? text.trim() : "";
+}