fix: simplify voice dictation providers
This commit is contained in:
1 parent
1dbfe76c62
commit
b5aa8b65cc
11 files changed
+263
-271
No files matched your search
@@ -34,9 +34,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarV2ConfiguredByUser: false,
|
||||
timestampFormat: "24-hour",
|
||||
voiceTranscriptionEnabled: true,
|
||||
voiceTranscriptionProvider: "local",
|
||||
voiceTranscriptionBaseUrl: "http://127.0.0.1:8080/v1",
|
||||
voiceTranscriptionModel: "whisper-1",
|
||||
voiceTranscriptionProvider: "openai",
|
||||
voiceTranscriptionApiKey: "",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
+32
-20
@@ -40,7 +40,13 @@ import {
|
||||
} from "./auth/http.ts";
|
||||
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
|
||||
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
|
||||
import { forwardWhisperTranscription, MAX_TRANSCRIPTION_AUDIO_BYTES } from "./transcription.ts";
|
||||
import {
|
||||
forwardVoiceTranscription,
|
||||
MAX_TRANSCRIPTION_AUDIO_BYTES,
|
||||
readTranscriptionAudio,
|
||||
resolveTranscriptionProvider,
|
||||
TranscriptionInputError,
|
||||
} from "./transcription.ts";
|
||||
|
||||
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
|
||||
const TRANSCRIPTION_PATH = "/api/transcription";
|
||||
@@ -263,32 +269,38 @@ export const transcriptionRouteLayer = HttpRouter.add(
|
||||
);
|
||||
}
|
||||
|
||||
const body = yield* request.arrayBuffer;
|
||||
const audio = new Uint8Array(body);
|
||||
const result = yield* Effect.tryPromise(() =>
|
||||
forwardWhisperTranscription({
|
||||
audio,
|
||||
audioMimeType: request.headers["content-type"] ?? "audio/webm",
|
||||
baseUrl: request.headers["x-t3-transcription-base-url"] ?? "",
|
||||
model: request.headers["x-t3-transcription-model"] ?? "",
|
||||
apiKey: request.headers["x-t3-transcription-api-key"] ?? "",
|
||||
}),
|
||||
).pipe(
|
||||
Effect.orElseSucceed(() => ({
|
||||
ok: false as const,
|
||||
status: 502,
|
||||
message: "Transcription failed unexpectedly.",
|
||||
})),
|
||||
const provider = resolveTranscriptionProvider(
|
||||
request.headers["x-t3-transcription-provider"] ?? "",
|
||||
);
|
||||
if (!provider) {
|
||||
return yield* new TranscriptionInputError({ reason: "invalid_provider" });
|
||||
}
|
||||
|
||||
return result.ok
|
||||
? HttpServerResponse.jsonUnsafe({ text: result.text })
|
||||
: HttpServerResponse.jsonUnsafe({ error: result.message }, { status: result.status });
|
||||
const audio = yield* readTranscriptionAudio(request.stream);
|
||||
const text = yield* forwardVoiceTranscription({
|
||||
audio,
|
||||
audioMimeType: request.headers["content-type"] ?? "audio/webm",
|
||||
provider,
|
||||
apiKey: request.headers["x-t3-transcription-api-key"] ?? "",
|
||||
});
|
||||
return HttpServerResponse.jsonUnsafe({ text });
|
||||
}).pipe(
|
||||
Effect.catchTags({
|
||||
EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
|
||||
EnvironmentInternalError: HttpServerRespondable.toResponse,
|
||||
EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
|
||||
TranscriptionAudioTooLargeError: (error) =>
|
||||
Effect.succeed(HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 413 })),
|
||||
TranscriptionBodyReadError: (error) =>
|
||||
Effect.succeed(HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 400 })),
|
||||
TranscriptionInputError: (error) =>
|
||||
Effect.succeed(HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 400 })),
|
||||
TranscriptionProviderError: (error) =>
|
||||
Effect.succeed(HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 502 })),
|
||||
TranscriptionRequestError: (error) =>
|
||||
Effect.succeed(HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 502 })),
|
||||
TranscriptionResponseError: (error) =>
|
||||
Effect.succeed(HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 502 })),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -6,8 +6,7 @@ export const browserApiCorsAllowedHeaders = [
|
||||
"content-type",
|
||||
"dpop",
|
||||
"x-t3-transcription-api-key",
|
||||
"x-t3-transcription-base-url",
|
||||
"x-t3-transcription-model",
|
||||
"x-t3-transcription-provider",
|
||||
] as const;
|
||||
|
||||
export const browserApiCorsHeaders = {
|
||||
|
||||
@@ -1300,6 +1300,8 @@ const assertBrowserApiCorsPreflightHeaders = (
|
||||
"content-type",
|
||||
"dpop",
|
||||
"traceparent",
|
||||
"x-t3-transcription-api-key",
|
||||
"x-t3-transcription-provider",
|
||||
]);
|
||||
};
|
||||
const crossOriginClientOrigin = "http://remote-client.test:3773";
|
||||
@@ -4209,6 +4211,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
"content-type",
|
||||
"dpop",
|
||||
"traceparent",
|
||||
"x-t3-transcription-api-key",
|
||||
"x-t3-transcription-provider",
|
||||
]);
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
@@ -1,66 +1,50 @@
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { describe, vi } from "vite-plus/test";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { describe } from "vite-plus/test";
|
||||
|
||||
import { forwardWhisperTranscription, resolveWhisperTranscriptionUrl } from "./transcription.ts";
|
||||
import {
|
||||
MAX_TRANSCRIPTION_AUDIO_BYTES,
|
||||
readTranscriptionAudio,
|
||||
resolveTranscriptionProvider,
|
||||
transcriptionProviderConfig,
|
||||
} from "./transcription.ts";
|
||||
|
||||
describe("resolveWhisperTranscriptionUrl", () => {
|
||||
it("adds the OpenAI-compatible transcription path", () => {
|
||||
expect(resolveWhisperTranscriptionUrl("http://127.0.0.1:8080/v1/")?.toString()).toBe(
|
||||
"http://127.0.0.1:8080/v1/audio/transcriptions",
|
||||
);
|
||||
expect(
|
||||
resolveWhisperTranscriptionUrl(
|
||||
"https://api.groq.com/openai/v1/audio/transcriptions",
|
||||
)?.toString(),
|
||||
).toBe("https://api.groq.com/openai/v1/audio/transcriptions");
|
||||
});
|
||||
|
||||
it("rejects non-http and credential-bearing URLs", () => {
|
||||
expect(resolveWhisperTranscriptionUrl("file:///tmp/whisper")).toBeNull();
|
||||
expect(resolveWhisperTranscriptionUrl("https://user:[email protected]/v1")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("forwardWhisperTranscription", () => {
|
||||
it("sends OpenAI-compatible multipart audio with BYOK authorization", async () => {
|
||||
const fetchImpl = vi.fn(async (_input: string | URL | Request, init?: RequestInit) => {
|
||||
expect(init?.headers).toEqual({ authorization: "Bearer groq-key" });
|
||||
expect(init?.body).toBeInstanceOf(FormData);
|
||||
const form = init?.body as FormData;
|
||||
expect(form.get("model")).toBe("whisper-large-v3-turbo");
|
||||
expect(form.get("file")).toBeInstanceOf(Blob);
|
||||
return Response.json({ text: "hello from the microphone" });
|
||||
describe("transcription providers", () => {
|
||||
it("uses a fixed OpenAI endpoint and model", () => {
|
||||
expect(resolveTranscriptionProvider("openai")).toBe("openai");
|
||||
expect(transcriptionProviderConfig("openai")).toEqual({
|
||||
endpoint: "https://api.openai.com/v1/audio/transcriptions",
|
||||
model: "gpt-4o-mini-transcribe",
|
||||
});
|
||||
|
||||
await expect(
|
||||
forwardWhisperTranscription(
|
||||
{
|
||||
audio: new Uint8Array([1, 2, 3]),
|
||||
audioMimeType: "audio/webm;codecs=opus",
|
||||
baseUrl: "https://api.groq.com/openai/v1",
|
||||
model: "whisper-large-v3-turbo",
|
||||
apiKey: "groq-key",
|
||||
},
|
||||
fetchImpl,
|
||||
),
|
||||
).resolves.toEqual({ ok: true, text: "hello from the microphone" });
|
||||
});
|
||||
|
||||
it("returns a safe provider error", async () => {
|
||||
const fetchImpl = vi.fn(async () =>
|
||||
Response.json({ error: { message: "bad key" } }, { status: 401 }),
|
||||
);
|
||||
await expect(
|
||||
forwardWhisperTranscription(
|
||||
{
|
||||
audio: new Uint8Array([1]),
|
||||
audioMimeType: "audio/webm",
|
||||
baseUrl: "https://example.com/v1",
|
||||
model: "whisper-1",
|
||||
apiKey: "bad",
|
||||
},
|
||||
fetchImpl,
|
||||
),
|
||||
).resolves.toEqual({ ok: false, status: 502, message: "bad key" });
|
||||
it("uses a fixed Groq endpoint and rejects custom providers", () => {
|
||||
expect(resolveTranscriptionProvider("groq")).toBe("groq");
|
||||
expect(transcriptionProviderConfig("groq")).toEqual({
|
||||
endpoint: "https://api.groq.com/openai/v1/audio/transcriptions",
|
||||
model: "whisper-large-v3-turbo",
|
||||
});
|
||||
expect(resolveTranscriptionProvider("http://127.0.0.1:8080/v1")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("readTranscriptionAudio", () => {
|
||||
it.effect("combines streamed audio chunks", () =>
|
||||
Effect.gen(function* () {
|
||||
const audio = yield* readTranscriptionAudio(
|
||||
Stream.make(new Uint8Array([1, 2]), new Uint8Array([3, 4])),
|
||||
);
|
||||
expect(Array.from(audio)).toEqual([1, 2, 3, 4]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stops when streamed audio exceeds the limit", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* readTranscriptionAudio(
|
||||
Stream.make(new Uint8Array(MAX_TRANSCRIPTION_AUDIO_BYTES), new Uint8Array([1])),
|
||||
).pipe(Effect.flip);
|
||||
expect(error._tag).toBe("TranscriptionAudioTooLargeError");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,38 +1,127 @@
|
||||
const TRANSCRIPTION_PATH = "/audio/transcriptions";
|
||||
import type { VoiceTranscriptionProvider } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
|
||||
|
||||
export const MAX_TRANSCRIPTION_AUDIO_BYTES = 25 * 1024 * 1024;
|
||||
|
||||
export interface WhisperTranscriptionInput {
|
||||
const PROVIDERS = {
|
||||
openai: {
|
||||
endpoint: "https://api.openai.com/v1/audio/transcriptions",
|
||||
model: "gpt-4o-mini-transcribe",
|
||||
},
|
||||
groq: {
|
||||
endpoint: "https://api.groq.com/openai/v1/audio/transcriptions",
|
||||
model: "whisper-large-v3-turbo",
|
||||
},
|
||||
} as const satisfies Record<VoiceTranscriptionProvider, { endpoint: string; model: string }>;
|
||||
|
||||
export interface VoiceTranscriptionInput {
|
||||
readonly audio: Uint8Array;
|
||||
readonly audioMimeType: string;
|
||||
readonly baseUrl: string;
|
||||
readonly model: string;
|
||||
readonly provider: VoiceTranscriptionProvider;
|
||||
readonly apiKey: string;
|
||||
}
|
||||
|
||||
type TranscriptionFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
||||
|
||||
export type WhisperTranscriptionResult =
|
||||
| { readonly ok: true; readonly text: string }
|
||||
| { readonly ok: false; readonly status: number; readonly message: string };
|
||||
|
||||
export function resolveWhisperTranscriptionUrl(baseUrl: string): URL | null {
|
||||
try {
|
||||
const url = new URL(baseUrl.trim());
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
|
||||
if (url.username || url.password) return null;
|
||||
url.search = "";
|
||||
url.hash = "";
|
||||
url.pathname = url.pathname.replace(/\/$/, "");
|
||||
if (!url.pathname.endsWith(TRANSCRIPTION_PATH)) {
|
||||
url.pathname += TRANSCRIPTION_PATH;
|
||||
}
|
||||
return url;
|
||||
} catch {
|
||||
return null;
|
||||
export class TranscriptionAudioTooLargeError extends Schema.TaggedErrorClass<TranscriptionAudioTooLargeError>()(
|
||||
"TranscriptionAudioTooLargeError",
|
||||
{ receivedBytes: Schema.Number },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The recording exceeds the 25 MB limit.";
|
||||
}
|
||||
}
|
||||
|
||||
export class TranscriptionBodyReadError extends Schema.TaggedErrorClass<TranscriptionBodyReadError>()(
|
||||
"TranscriptionBodyReadError",
|
||||
{ cause: Schema.Defect() },
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not read the recording.";
|
||||
}
|
||||
}
|
||||
|
||||
export class TranscriptionInputError extends Schema.TaggedErrorClass<TranscriptionInputError>()(
|
||||
"TranscriptionInputError",
|
||||
{ reason: Schema.Literals(["empty_audio", "invalid_provider", "missing_api_key"]) },
|
||||
) {
|
||||
override get message(): string {
|
||||
if (this.reason === "empty_audio") return "The recording was empty.";
|
||||
if (this.reason === "invalid_provider") return "Select OpenAI or Groq for transcription.";
|
||||
return "Add an API key for the selected transcription provider.";
|
||||
}
|
||||
}
|
||||
|
||||
export class TranscriptionRequestError extends Schema.TaggedErrorClass<TranscriptionRequestError>()(
|
||||
"TranscriptionRequestError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Could not reach the transcription provider.";
|
||||
}
|
||||
}
|
||||
|
||||
export class TranscriptionProviderError extends Schema.TaggedErrorClass<TranscriptionProviderError>()(
|
||||
"TranscriptionProviderError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
providerStatus: Schema.Int,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The transcription provider rejected the request. Check the provider and API key.";
|
||||
}
|
||||
}
|
||||
|
||||
export class TranscriptionResponseError extends Schema.TaggedErrorClass<TranscriptionResponseError>()(
|
||||
"TranscriptionResponseError",
|
||||
{
|
||||
provider: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "The transcription provider returned an invalid response.";
|
||||
}
|
||||
}
|
||||
|
||||
const TranscriptionResponse = Schema.Struct({ text: Schema.String });
|
||||
|
||||
export function resolveTranscriptionProvider(provider: string): VoiceTranscriptionProvider | null {
|
||||
return provider === "openai" || provider === "groq" ? provider : null;
|
||||
}
|
||||
|
||||
export function transcriptionProviderConfig(provider: VoiceTranscriptionProvider) {
|
||||
return PROVIDERS[provider];
|
||||
}
|
||||
|
||||
export const readTranscriptionAudio = <E, R>(stream: Stream.Stream<Uint8Array, E, R>) =>
|
||||
stream.pipe(
|
||||
Stream.mapError((cause) => new TranscriptionBodyReadError({ cause })),
|
||||
Stream.runFoldEffect(
|
||||
() => ({ chunks: [] as Uint8Array[], size: 0 }),
|
||||
(accumulator, chunk) => {
|
||||
const size = accumulator.size + chunk.byteLength;
|
||||
return size > MAX_TRANSCRIPTION_AUDIO_BYTES
|
||||
? Effect.fail(new TranscriptionAudioTooLargeError({ receivedBytes: size }))
|
||||
: Effect.succeed({ chunks: [...accumulator.chunks, chunk], size });
|
||||
},
|
||||
),
|
||||
Effect.map(({ chunks, size }) => {
|
||||
const audio = new Uint8Array(size);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
audio.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return audio;
|
||||
}),
|
||||
);
|
||||
|
||||
function audioFileExtension(mimeType: string): string {
|
||||
if (mimeType.includes("ogg")) return "ogg";
|
||||
if (mimeType.includes("mp4") || mimeType.includes("m4a")) return "m4a";
|
||||
@@ -40,74 +129,50 @@ function audioFileExtension(mimeType: string): string {
|
||||
return "webm";
|
||||
}
|
||||
|
||||
export async function forwardWhisperTranscription(
|
||||
input: WhisperTranscriptionInput,
|
||||
fetchImpl: TranscriptionFetch = globalThis.fetch,
|
||||
): Promise<WhisperTranscriptionResult> {
|
||||
const endpoint = resolveWhisperTranscriptionUrl(input.baseUrl);
|
||||
if (!endpoint) {
|
||||
return { ok: false, status: 400, message: "Enter a valid HTTP transcription endpoint." };
|
||||
}
|
||||
if (!input.model.trim()) {
|
||||
return { ok: false, status: 400, message: "Enter a transcription model." };
|
||||
}
|
||||
export const forwardVoiceTranscription = Effect.fn("voiceTranscription.forward")(function* (
|
||||
input: VoiceTranscriptionInput,
|
||||
) {
|
||||
if (input.audio.byteLength === 0) {
|
||||
return { ok: false, status: 400, message: "The recording was empty." };
|
||||
return yield* new TranscriptionInputError({ reason: "empty_audio" });
|
||||
}
|
||||
if (input.audio.byteLength > MAX_TRANSCRIPTION_AUDIO_BYTES) {
|
||||
return { ok: false, status: 413, message: "The recording exceeds the 25 MB limit." };
|
||||
return yield* new TranscriptionAudioTooLargeError({
|
||||
receivedBytes: input.audio.byteLength,
|
||||
});
|
||||
}
|
||||
const apiKey = input.apiKey.trim();
|
||||
if (!apiKey) {
|
||||
return yield* new TranscriptionInputError({ reason: "missing_api_key" });
|
||||
}
|
||||
|
||||
const providerConfig = transcriptionProviderConfig(input.provider);
|
||||
const mimeType = input.audioMimeType.split(";", 1)[0]?.trim() || "audio/webm";
|
||||
const form = new FormData();
|
||||
form.set("model", input.model.trim());
|
||||
form.set("model", providerConfig.model);
|
||||
form.set(
|
||||
"file",
|
||||
new Blob([input.audio], { type: mimeType }),
|
||||
`recording.${audioFileExtension(mimeType)}`,
|
||||
);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetchImpl(endpoint, {
|
||||
method: "POST",
|
||||
headers: input.apiKey ? { authorization: `Bearer ${input.apiKey}` } : undefined,
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const response = yield* HttpClientRequest.post(providerConfig.endpoint).pipe(
|
||||
HttpClientRequest.bearerToken(apiKey),
|
||||
HttpClientRequest.bodyFormData(form),
|
||||
httpClient.execute,
|
||||
Effect.timeout("2 minutes"),
|
||||
Effect.mapError((cause) => new TranscriptionRequestError({ provider: input.provider, cause })),
|
||||
);
|
||||
|
||||
if (response.status < 200 || response.status >= 300) {
|
||||
return yield* new TranscriptionProviderError({
|
||||
provider: input.provider,
|
||||
providerStatus: response.status,
|
||||
});
|
||||
} catch {
|
||||
return { ok: false, status: 502, message: "Could not reach the transcription provider." };
|
||||
}
|
||||
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = await response.json();
|
||||
} catch {
|
||||
return { ok: false, status: 502, message: "The transcription provider returned invalid JSON." };
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const providerMessage =
|
||||
typeof payload === "object" &&
|
||||
payload !== null &&
|
||||
"error" in payload &&
|
||||
typeof payload.error === "object" &&
|
||||
payload.error !== null &&
|
||||
"message" in payload.error &&
|
||||
typeof payload.error.message === "string"
|
||||
? payload.error.message
|
||||
: null;
|
||||
return {
|
||||
ok: false,
|
||||
status: 502,
|
||||
message: providerMessage?.slice(0, 300) || "The transcription provider rejected the request.",
|
||||
};
|
||||
}
|
||||
|
||||
const text =
|
||||
typeof payload === "object" && payload !== null && "text" in payload ? payload.text : undefined;
|
||||
if (typeof text !== "string") {
|
||||
return { ok: false, status: 502, message: "The transcription response did not contain text." };
|
||||
}
|
||||
return { ok: true, text: text.trim() };
|
||||
}
|
||||
const payload = yield* HttpClientResponse.schemaBodyJson(TranscriptionResponse)(response).pipe(
|
||||
Effect.mapError((cause) => new TranscriptionResponseError({ provider: input.provider, cause })),
|
||||
);
|
||||
return payload.text.trim();
|
||||
});
|
||||
@@ -1289,8 +1289,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const voiceTranscription = useVoiceTranscription({
|
||||
config: {
|
||||
provider: settings.voiceTranscriptionProvider,
|
||||
baseUrl: settings.voiceTranscriptionBaseUrl,
|
||||
model: settings.voiceTranscriptionModel,
|
||||
apiKey: settings.voiceTranscriptionApiKey,
|
||||
},
|
||||
onTranscript: appendVoiceTranscript,
|
||||
@@ -3129,7 +3127,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{settings.voiceTranscriptionEnabled && voiceTranscription.status !== "idle" ? (
|
||||
{voiceTranscription.status !== "idle" ? (
|
||||
<VoiceTranscriptionPanel
|
||||
status={voiceTranscription.status}
|
||||
elapsedMs={voiceTranscription.elapsedMs}
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
DEFAULT_VOICE_TRANSCRIPTION_BASE_URL,
|
||||
DEFAULT_VOICE_TRANSCRIPTION_MODEL,
|
||||
type VoiceTranscriptionProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import type { VoiceTranscriptionProvider } from "@t3tools/contracts";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import {
|
||||
@@ -10,10 +6,6 @@ import {
|
||||
useSidebarV2Enabled,
|
||||
useUpdateClientSettings,
|
||||
} from "../../hooks/useSettings";
|
||||
import {
|
||||
GROQ_TRANSCRIPTION_BASE_URL,
|
||||
GROQ_TRANSCRIPTION_MODEL,
|
||||
} from "../../lib/voiceTranscription";
|
||||
import { Input } from "../ui/input";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
@@ -76,35 +68,11 @@ export function BetaSettingsPanel() {
|
||||
const voiceTranscriptionProvider = useClientSettings(
|
||||
(settings) => settings.voiceTranscriptionProvider,
|
||||
);
|
||||
const voiceTranscriptionBaseUrl = useClientSettings(
|
||||
(settings) => settings.voiceTranscriptionBaseUrl,
|
||||
);
|
||||
const voiceTranscriptionModel = useClientSettings((settings) => settings.voiceTranscriptionModel);
|
||||
const voiceTranscriptionApiKey = useClientSettings(
|
||||
(settings) => settings.voiceTranscriptionApiKey,
|
||||
);
|
||||
const updateSettings = useUpdateClientSettings();
|
||||
|
||||
const selectVoiceProvider = (provider: VoiceTranscriptionProvider) => {
|
||||
if (provider === "local") {
|
||||
updateSettings({
|
||||
voiceTranscriptionProvider: provider,
|
||||
voiceTranscriptionBaseUrl: DEFAULT_VOICE_TRANSCRIPTION_BASE_URL,
|
||||
voiceTranscriptionModel: DEFAULT_VOICE_TRANSCRIPTION_MODEL,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (provider === "groq") {
|
||||
updateSettings({
|
||||
voiceTranscriptionProvider: provider,
|
||||
voiceTranscriptionBaseUrl: GROQ_TRANSCRIPTION_BASE_URL,
|
||||
voiceTranscriptionModel: GROQ_TRANSCRIPTION_MODEL,
|
||||
});
|
||||
return;
|
||||
}
|
||||
updateSettings({ voiceTranscriptionProvider: provider });
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection title="Beta features">
|
||||
@@ -174,72 +142,36 @@ export function BetaSettingsPanel() {
|
||||
<>
|
||||
<SettingsRow
|
||||
title="Transcription provider"
|
||||
description="Local is the default and works with an OpenAI-compatible whisper.cpp or faster-whisper server."
|
||||
description="Use your own OpenAI or Groq key. OpenAI is the default."
|
||||
control={
|
||||
<Select
|
||||
value={voiceTranscriptionProvider}
|
||||
onValueChange={(value) =>
|
||||
selectVoiceProvider(value as VoiceTranscriptionProvider)
|
||||
updateSettings({
|
||||
voiceTranscriptionProvider: value as VoiceTranscriptionProvider,
|
||||
voiceTranscriptionApiKey: "",
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-44" aria-label="Transcription provider">
|
||||
<SelectValue>
|
||||
{voiceTranscriptionProvider === "local"
|
||||
? "Local"
|
||||
: voiceTranscriptionProvider === "groq"
|
||||
? "Groq"
|
||||
: "Custom"}
|
||||
{voiceTranscriptionProvider === "openai" ? "OpenAI" : "Groq"}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
<SelectItem hideIndicator value="local">
|
||||
Local
|
||||
<SelectItem hideIndicator value="openai">
|
||||
OpenAI
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="groq">
|
||||
Groq
|
||||
</SelectItem>
|
||||
<SelectItem hideIndicator value="custom">
|
||||
Custom
|
||||
</SelectItem>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
title="Endpoint"
|
||||
description="Base URL for any OpenAI Whisper-compatible API."
|
||||
control={
|
||||
<Input
|
||||
className="w-full sm:w-80"
|
||||
value={voiceTranscriptionBaseUrl}
|
||||
onChange={(event) =>
|
||||
updateSettings({ voiceTranscriptionBaseUrl: event.target.value })
|
||||
}
|
||||
placeholder="http://127.0.0.1:8080/v1"
|
||||
aria-label="Transcription endpoint"
|
||||
spellCheck={false}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
title="Model"
|
||||
description="The model name sent to the provider."
|
||||
control={
|
||||
<Input
|
||||
className="w-full sm:w-64"
|
||||
value={voiceTranscriptionModel}
|
||||
onChange={(event) =>
|
||||
updateSettings({ voiceTranscriptionModel: event.target.value })
|
||||
}
|
||||
placeholder="whisper-1"
|
||||
aria-label="Transcription model"
|
||||
spellCheck={false}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
title="API key"
|
||||
description="Optional for local servers and required by most hosted providers. The key stays in this client's local settings."
|
||||
title={`${voiceTranscriptionProvider === "openai" ? "OpenAI" : "Groq"} API key`}
|
||||
description="Stored only in this client's local settings and sent directly to the selected provider through your local t3code server."
|
||||
control={
|
||||
<Input
|
||||
type="password"
|
||||
@@ -249,7 +181,7 @@ export function BetaSettingsPanel() {
|
||||
onChange={(event) =>
|
||||
updateSettings({ voiceTranscriptionApiKey: event.target.value })
|
||||
}
|
||||
placeholder={voiceTranscriptionProvider === "local" ? "Optional" : "Required"}
|
||||
placeholder="Required"
|
||||
aria-label="Transcription API key"
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ export function useVoiceTranscription({
|
||||
const [levels, setLevels] = useState<readonly number[]>(() => Array(LEVEL_COUNT).fill(0.12));
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const recorderRef = useRef<MediaRecorder | null>(null);
|
||||
const startingRef = useRef(false);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
const audioContextRef = useRef<AudioContext | null>(null);
|
||||
const intervalsRef = useRef<number[]>([]);
|
||||
@@ -52,6 +53,7 @@ export function useVoiceTranscription({
|
||||
mountedRef.current = true;
|
||||
return () => {
|
||||
mountedRef.current = false;
|
||||
startingRef.current = false;
|
||||
const recorder = recorderRef.current;
|
||||
if (recorder?.state === "recording") recorder.stop();
|
||||
cleanupCapture();
|
||||
@@ -64,9 +66,11 @@ export function useVoiceTranscription({
|
||||
}, []);
|
||||
|
||||
const start = useCallback(async () => {
|
||||
if (status !== "idle") return;
|
||||
if (startingRef.current || status !== "idle") return;
|
||||
startingRef.current = true;
|
||||
setError(null);
|
||||
if (!navigator.mediaDevices?.getUserMedia || typeof MediaRecorder === "undefined") {
|
||||
startingRef.current = false;
|
||||
setError("Microphone recording is not supported on this device.");
|
||||
return;
|
||||
}
|
||||
@@ -77,24 +81,31 @@ export function useVoiceTranscription({
|
||||
});
|
||||
if (!mountedRef.current) {
|
||||
stream.getTracks().forEach((track) => track.stop());
|
||||
startingRef.current = false;
|
||||
return;
|
||||
}
|
||||
|
||||
streamRef.current = stream;
|
||||
const mimeType = supportedMimeType();
|
||||
const recorder = new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
|
||||
const chunks: Blob[] = [];
|
||||
streamRef.current = stream;
|
||||
let recordingFailed = false;
|
||||
recorderRef.current = recorder;
|
||||
recorder.addEventListener("dataavailable", (event) => {
|
||||
if (event.data.size > 0) chunks.push(event.data);
|
||||
});
|
||||
recorder.addEventListener("error", () => {
|
||||
if (mountedRef.current) setError("The microphone stopped unexpectedly.");
|
||||
recordingFailed = true;
|
||||
cleanupCapture();
|
||||
if (mountedRef.current) {
|
||||
setStatus("idle");
|
||||
setError("The microphone stopped unexpectedly.");
|
||||
}
|
||||
});
|
||||
recorder.addEventListener("stop", () => {
|
||||
const blob = new Blob(chunks, { type: recorder.mimeType || mimeType || "audio/webm" });
|
||||
cleanupCapture();
|
||||
if (!mountedRef.current) return;
|
||||
if (!mountedRef.current || recordingFailed) return;
|
||||
setStatus("transcribing");
|
||||
void transcribeVoiceRecording(blob, configRef.current)
|
||||
.then((text) => {
|
||||
@@ -133,8 +144,10 @@ export function useVoiceTranscription({
|
||||
);
|
||||
timeoutRef.current = window.setTimeout(() => recorder.stop(), MAX_RECORDING_MS);
|
||||
recorder.start(250);
|
||||
startingRef.current = false;
|
||||
setStatus("recording");
|
||||
} catch (cause) {
|
||||
startingRef.current = false;
|
||||
cleanupCapture();
|
||||
setStatus("idle");
|
||||
setError(
|
||||
|
||||
@@ -3,13 +3,8 @@ import type { VoiceTranscriptionProvider } from "@t3tools/contracts";
|
||||
import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth";
|
||||
import { resolvePrimaryEnvironmentHttpUrl } from "../environments/primary/target";
|
||||
|
||||
export const GROQ_TRANSCRIPTION_BASE_URL = "https://api.groq.com/openai/v1";
|
||||
export const GROQ_TRANSCRIPTION_MODEL = "whisper-large-v3-turbo";
|
||||
|
||||
export interface VoiceTranscriptionConfig {
|
||||
readonly provider: VoiceTranscriptionProvider;
|
||||
readonly baseUrl: string;
|
||||
readonly model: string;
|
||||
readonly apiKey: string;
|
||||
}
|
||||
|
||||
@@ -17,6 +12,9 @@ export async function transcribeVoiceRecording(
|
||||
audio: Blob,
|
||||
config: VoiceTranscriptionConfig,
|
||||
): Promise<string> {
|
||||
const apiKey = config.apiKey.trim();
|
||||
if (!apiKey) throw new Error("Add an API key for the selected transcription provider.");
|
||||
|
||||
const bearerToken = await readDesktopPrimaryBearerToken();
|
||||
const response = await globalThis.fetch(resolvePrimaryEnvironmentHttpUrl("/api/transcription"), {
|
||||
method: "POST",
|
||||
@@ -24,9 +22,8 @@ export async function transcribeVoiceRecording(
|
||||
headers: {
|
||||
...(bearerToken ? { authorization: `Bearer ${bearerToken}` } : {}),
|
||||
"content-type": audio.type || "audio/webm",
|
||||
"x-t3-transcription-base-url": config.baseUrl,
|
||||
"x-t3-transcription-model": config.model,
|
||||
...(config.apiKey ? { "x-t3-transcription-api-key": config.apiKey } : {}),
|
||||
"x-t3-transcription-provider": config.provider,
|
||||
"x-t3-transcription-api-key": apiKey,
|
||||
},
|
||||
body: audio,
|
||||
});
|
||||
|
||||
@@ -62,10 +62,8 @@ export const EnvironmentIdentificationMode = Schema.Literals(["artwork", "pill",
|
||||
export type EnvironmentIdentificationMode = typeof EnvironmentIdentificationMode.Type;
|
||||
export const DEFAULT_ENVIRONMENT_IDENTIFICATION_MODE: EnvironmentIdentificationMode = "artwork";
|
||||
|
||||
export const VoiceTranscriptionProvider = Schema.Literals(["local", "groq", "custom"]);
|
||||
export const VoiceTranscriptionProvider = Schema.Literals(["openai", "groq"]);
|
||||
export type VoiceTranscriptionProvider = typeof VoiceTranscriptionProvider.Type;
|
||||
export const DEFAULT_VOICE_TRANSCRIPTION_BASE_URL = "http://127.0.0.1:8080/v1";
|
||||
export const DEFAULT_VOICE_TRANSCRIPTION_MODEL = "whisper-1";
|
||||
|
||||
export const ClientSettingsSchema = Schema.Struct({
|
||||
autoOpenPlanSidebar: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
@@ -137,15 +135,9 @@ export const ClientSettingsSchema = Schema.Struct({
|
||||
),
|
||||
voiceTranscriptionEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
voiceTranscriptionProvider: VoiceTranscriptionProvider.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed("local" as const)),
|
||||
Schema.withDecodingDefault(Effect.succeed("openai" as const)),
|
||||
),
|
||||
voiceTranscriptionBaseUrl: TrimmedString.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_VOICE_TRANSCRIPTION_BASE_URL)),
|
||||
),
|
||||
voiceTranscriptionModel: TrimmedString.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(DEFAULT_VOICE_TRANSCRIPTION_MODEL)),
|
||||
),
|
||||
voiceTranscriptionApiKey: Schema.String.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
voiceTranscriptionApiKey: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
|
||||
wordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
});
|
||||
export type ClientSettings = typeof ClientSettingsSchema.Type;
|
||||
@@ -730,9 +722,7 @@ export const ClientSettingsPatch = Schema.Struct({
|
||||
timestampFormat: Schema.optionalKey(TimestampFormat),
|
||||
voiceTranscriptionEnabled: Schema.optionalKey(Schema.Boolean),
|
||||
voiceTranscriptionProvider: Schema.optionalKey(VoiceTranscriptionProvider),
|
||||
voiceTranscriptionBaseUrl: Schema.optionalKey(TrimmedString),
|
||||
voiceTranscriptionModel: Schema.optionalKey(TrimmedString),
|
||||
voiceTranscriptionApiKey: Schema.optionalKey(Schema.String),
|
||||
voiceTranscriptionApiKey: Schema.optionalKey(TrimmedString),
|
||||
wordWrap: Schema.optionalKey(Schema.Boolean),
|
||||
});
|
||||
export type ClientSettingsPatch = typeof ClientSettingsPatch.Type;
|
||||
Reference in new issue
Block a user