import { embeddingServerService, LOCAL_EMBEDDING_PROVIDER, } from '@shumai/core/src/search/embedding-server' import { transcriptLanguageCodeSchema, transcriptLanguagesSchema } from '@shumai/dtos' import { z } from 'zod' export async function isLocalTranscriptionEnabled(teamId?: string): Promise { const { provider } = await embeddingServerService.resolveRuntimeConfig(teamId) return provider === LOCAL_EMBEDDING_PROVIDER } export async function listLocalTranscriptionLanguages(teamId?: string) { const { transcriptionEndpoint } = await embeddingServerService.resolveRuntimeConfig(teamId) const response = await fetch(`${transcriptionEndpoint}/languages`, { signal: AbortSignal.timeout(5_000), }) if (!response.ok) throw new Error(`Transcription languages endpoint returned ${response.status}`) return transcriptLanguagesSchema.parse(await response.json()) } const transcriptResponseSchema = z .object({ language: transcriptLanguageCodeSchema.nullable(), segments: z.array( z .object({ start: z.number().min(0), end: z.number().min(0), text: z.string().min(1) }) .refine((segment) => segment.end >= segment.start && segment.end < 2_147_483), ), }) .refine((result) => result.language !== null || result.segments.length === 0) export class LocalTranscriptionError extends Error { constructor(readonly status: number) { super(`Transcription server returned HTTP ${status}`) } } export async function transcribeLocalAudio({ teamId, audio, language, model, signal, }: { teamId?: string audio: Blob language: string | null model: string signal?: AbortSignal }) { const form = new FormData() form.set('file', audio, 'audio.wav') form.set('model', model) form.set('response_format', 'verbose_json') if (language) form.set('language', language) const timeout = AbortSignal.timeout(90 * 60 * 1000) const { transcriptionEndpoint } = await embeddingServerService.resolveRuntimeConfig(teamId) const response = await fetch(transcriptionEndpoint, { method: 'POST', body: form, redirect: 'error', timeout: false, signal: signal ? AbortSignal.any([signal, timeout]) : timeout, }) if (!response.ok) { await response.body?.cancel() throw new LocalTranscriptionError(response.status) } return transcriptResponseSchema.parse(await response.json()) }