Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 2 additions & 26 deletions apps/server/src/speech/CloudSpeech.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { requireSettingsSecret } from "../secrets/settingsSecretValue.ts";
import { applySpeechAliases, speechRecognitionWords } from "./customWords.ts";
import { removeSpeechFillerWords } from "./fillerWords.ts";
import { decodeSpeechPcm, SpeechInvalidAudioError } from "./SpeechService.ts";
import { encodePcm16Wav } from "./wav.ts";

const endpoints = {
openai: { url: "https://api.openai.com/v1/audio/transcriptions", model: "gpt-transcribe" },
Expand All @@ -41,31 +42,6 @@ const OpenRouterCatalog = Schema.Struct({
data: Schema.Array(Schema.Struct({ id: Schema.String, name: Schema.optionalKey(Schema.String) })),
});

function wave(samples: Float32Array) {
const buffer = new ArrayBuffer(44 + samples.length * 2);
const view = new DataView(buffer);
const tag = (at: number, value: string) =>
new Uint8Array(buffer, at, 4).set(new TextEncoder().encode(value));
tag(0, "RIFF");
view.setUint32(4, buffer.byteLength - 8, true);
tag(8, "WAVE");
tag(12, "fmt ");
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, 1, true);
view.setUint32(24, 16_000, true);
view.setUint32(28, 32_000, true);
view.setUint16(32, 2, true);
view.setUint16(34, 16, true);
tag(36, "data");
view.setUint32(40, buffer.byteLength - 44, true);
for (let index = 0; index < samples.length; index++) {
const sample = samples[index]!;
view.setInt16(44 + index * 2, Math.round(sample * (sample < 0 ? 32768 : 32767)), true);
}
return buffer;
}

function audioBody(
provider: "openai" | "xai",
audio: ArrayBuffer,
Expand Down Expand Up @@ -210,7 +186,7 @@ export const layer = Layer.effect(
Effect.mapError(unreadable),
);
if (!isApiKey(key)) return yield* unreadable();
const audio = wave(samples);
const audio = encodePcm16Wav(samples);
const request = HttpClientRequest.post(endpoints[provider].url).pipe(
HttpClientRequest.bearerToken(Redacted.make(key)),
provider === "openrouter"
Expand Down
165 changes: 160 additions & 5 deletions apps/server/src/speech/SpeechService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ import * as Stream from "effect/Stream";

import * as ServerSettings from "../serverSettings.ts";
import {
applySpeechAliases,
makeSpeechTextCorrector,
normalizeSpeechCustomWords,
speechRecognitionWords,
} from "./customWords.ts";
import { removeSpeechFillerWords } from "./fillerWords.ts";
import { parseLocalSpeechEndpoint, transcribeWithLocalEndpoint } from "./localEndpoint.ts";
import {
DEFAULT_SPEECH_MODEL_ID,
effectiveSpeechLanguage,
Expand Down Expand Up @@ -458,6 +460,29 @@ const make = Effect.gen(function* () {
const currentStatus = Effect.fn("SpeechService.currentStatus")(function* (
settings: SettingsSnapshot,
): Effect.fn.Return<EnvironmentSpeechStatus> {
const localEndpoint = parseLocalSpeechEndpoint(
settings.speechLocalEndpointUrl,
settings.speechLocalEndpointModel,
);
if (localEndpoint) {
return {
supported: true,
state: activeTranscriptions > 0 ? "transcribing" : "ready",
modelId: localEndpoint.model,
model: `Local STT (${localEndpoint.model})`,
size: 0,
supportsStreaming: true,
supportsBufferedStreaming: true,
supportsModelLinking: !unsupportedReason,
supportsTranslation: false,
languages: ["en"],
supportsLanguageDetection: true,
acceleration: settings.speechAcceleration,
benchmarkTier: "accelerated",
modelUnloadTimeout: settings.speechModelUnloadTimeout,
gpuDevices: [],
};
}
if (unsupportedReason) return { supported: false, reason: unsupportedReason };
const definition = selectedModel(settings);
const ready = yield* store.isReady(definition);
Expand Down Expand Up @@ -560,8 +585,13 @@ const make = Effect.gen(function* () {
};

const prepareModel = readSettings("model preparation").pipe(
Effect.flatMap((settings) =>
exclusive(
Effect.flatMap((settings) => {
if (
parseLocalSpeechEndpoint(settings.speechLocalEndpointUrl, settings.speechLocalEndpointModel)
) {
return Effect.void;
}
return exclusive(
"model preparation",
requireSupported.pipe(
Effect.andThen(installedModelPath(selectedModel(settings))),
Expand All @@ -582,8 +612,8 @@ const make = Effect.gen(function* () {
),
),
),
),
),
);
}),
);

const silenceModelPath = Effect.fn("SpeechService.silenceModelPath")(function* (
Expand All @@ -599,16 +629,46 @@ const make = Effect.gen(function* () {
const transcribe: SpeechService["Service"]["transcribe"] = Effect.fn("SpeechService.transcribe")(
function* (pcmBytes, options) {
const settings = yield* readSettings("transcription");
const localEndpoint = parseLocalSpeechEndpoint(
settings.speechLocalEndpointUrl,
settings.speechLocalEndpointModel,
);
return yield* exclusive(
"transcription",
Effect.gen(function* () {
yield* requireSupported;
if (!localEndpoint) yield* requireSupported;
const pcm = yield* Effect.try({
try: () => decodeSpeechPcm(pcmBytes),
catch: (cause) => speechError("transcription", cause),
});
if (pcm.length === 0) return "";
activeTranscriptions += 1;
if (localEndpoint) {
return yield* Effect.tryPromise({
try: (signal) =>
transcribeWithLocalEndpoint(
localEndpoint,
pcm,
options,
AbortSignal.any([signal, lifetime.signal]),
),
catch: (cause) => speechError("local endpoint transcription", cause),
}).pipe(
Effect.map((raw) => {
const corrected = applySpeechAliases(raw, options.speechCustomWords);
return finalizeTranscript(
corrected,
options,
options.speechLanguage === "auto" ? undefined : options.speechLanguage,
);
}),
Effect.ensuring(
Effect.sync(() => {
activeTranscriptions -= 1;
}),
),
);
}
return yield* Effect.gen(function* () {
const definition = selectedModel(settings);
const language = effectiveSpeechLanguage(definition, options.speechLanguage);
Expand Down Expand Up @@ -707,6 +767,101 @@ const make = Effect.gen(function* () {
// Stream setup shares the public startStream span.
const openStream = Effect.fnUntraced(function* (options: SpeechTranscriptionOptions) {
const operation = "streaming transcription";
const initialSettings = yield* readSettings(operation);
const localEndpoint = parseLocalSpeechEndpoint(
initialSettings.speechLocalEndpointUrl,
initialSettings.speechLocalEndpointModel,
);
if (localEndpoint) {
const released = Promise.withResolvers<void>();
// @effect-diagnostics-next-line abortControllerInEffect:off - Stream cancellation must abort in-flight HTTP fetch independently of the caller fiber.
const controller = new AbortController();
const signal = AbortSignal.any([controller.signal, lifetime.signal]);
const chunks: Float32Array[] = [];
let totalSamples = 0;
let totalBytes = 0;
let lastPreviewSamples = 0;
let latestPreview: string | null = null;
let previewInFlight = false;
let revision = 0;
let closed = false;
const combineChunks = () => {
const combined = new Float32Array(totalSamples);
let offset = 0;
for (const chunk of chunks) {
combined.set(chunk, offset);
offset += chunk.length;
}
return combined;
};
yield* Effect.acquireRelease(
Effect.suspend(() => {
if (closing || operationBusy()) return Effect.fail(new SpeechBusyError({ operation }));
activeOperation = released.promise;
activeTranscriptions += 1;
return Effect.void;
}),
() =>
Effect.sync(() => {
closed = true;
controller.abort();
activeTranscriptions -= 1;
if (activeOperation === released.promise) activeOperation = undefined;
released.resolve();
}),
);
return {
feed: (bytes: Uint8Array) =>
attempt(operation, async () => {
if (closed || signal.aborted) throw new Error("Speech stream is closed.");
if (
bytes.byteLength > SPEECH_STREAM_MAX_CHUNK_BYTES ||
totalBytes + bytes.byteLength > MAX_SPEECH_BYTES
) {
throw new SpeechInvalidAudioError({
byteLength: bytes.byteLength,
message: "Speech stream audio limit exceeded.",
});
}
const pcm = decodeSpeechPcm(bytes);
chunks.push(pcm);
totalSamples += pcm.length;
totalBytes += bytes.byteLength;
revision += 1;
// Phase 1 live preview: refresh interim text roughly every 1.5s of new audio.
if (!previewInFlight && totalSamples - lastPreviewSamples >= 24_000) {
previewInFlight = true;
lastPreviewSamples = totalSamples;
const snapshot = combineChunks();
void transcribeWithLocalEndpoint(localEndpoint, snapshot, options, signal)
.then((raw) => {
if (closed || signal.aborted) return;
const corrected = applySpeechAliases(raw, options.speechCustomWords).trim();
if (corrected) latestPreview = corrected;
})
.catch(() => undefined)
.finally(() => {
previewInFlight = false;
});
}
return {
revision,
text: latestPreview ? { committed: "", tentative: latestPreview } : null,
};
}),
finish: attempt(operation, async () => {
if (totalSamples === 0) return "";
const combined = combineChunks();
const raw = await transcribeWithLocalEndpoint(localEndpoint, combined, options, signal);
const corrected = applySpeechAliases(raw, options.speechCustomWords);
return finalizeTranscript(
corrected,
options,
options.speechLanguage === "auto" ? undefined : options.speechLanguage,
);
}),
};
}
yield* requireSupported;
const released = Promise.withResolvers<void>();
// @effect-diagnostics-next-line abortControllerInEffect:off - Stream cancellation must abort native work independently of the caller fiber.
Expand Down
59 changes: 59 additions & 0 deletions apps/server/src/speech/localCleanup.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { describe, expect, it, vi } from "vite-plus/test";

import {
cleanTranscriptLocally,
cleanTranscriptWithLocalEndpoint,
parseLocalCleanupEndpoint,
} from "./localCleanup.ts";

describe("localCleanup", () => {
it("cleans capitalization, contractions, stutters, punctuation, and spoken corrections locally", () => {
expect(
cleanTranscriptLocally("i dont think the the parser works right", { customWords: [] }),
).toBe("I don't think the parser works right.");

expect(cleanTranscriptLocally("can you check why tests fail", { customWords: [] })).toBe(
"Can you check why tests fail?",
);

expect(cleanTranscriptLocally("set timeout to 42, scratch that, 24", { customWords: [] })).toBe(
"Set timeout to 24.",
);

expect(
cleanTranscriptLocally("use m3 code for local voice", {
customWords: [{ term: "M3 Code", aliases: ["m3 code"] }],
}),
).toBe("Use M3 Code for local voice.");
});

it("parses valid local cleanup endpoints", () => {
expect(
parseLocalCleanupEndpoint("http://127.0.0.1:11434/v1/chat/completions", "qwen2.5:3b"),
).toEqual({
url: "http://127.0.0.1:11434/v1/chat/completions",
model: "qwen2.5:3b",
});
expect(parseLocalCleanupEndpoint("", "")).toBeNull();
expect(parseLocalCleanupEndpoint("file:///tmp/x", "")).toBeNull();
});

it("calls a local OpenAI-compatible chat completions endpoint for Phase 2 cleanup", async () => {
using _fetch = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(
JSON.stringify({
choices: [{ message: { content: "Fix the failing parser tests." } }],
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
);

const cleaned = await cleanTranscriptWithLocalEndpoint(
{ url: "http://127.0.0.1:11434/v1/chat/completions", model: "qwen2.5:3b" },
"fix the failing parser tests",
"Clean up punctuation and capitals.",
[],
);
expect(cleaned).toBe("Fix the failing parser tests.");
});
});
Loading
Loading