|
| 1 | +import type { FastifyInstance } from "fastify" |
| 2 | +import { z } from "zod" |
| 3 | +import type { SpeechService } from "../../speech/service" |
| 4 | + |
| 5 | +interface RouteDeps { |
| 6 | + speechService: SpeechService |
| 7 | +} |
| 8 | + |
| 9 | +const TranscribeBodySchema = z.object({ |
| 10 | + audioBase64: z.string().min(1, "Audio payload is required"), |
| 11 | + mimeType: z.string().min(1, "Audio MIME type is required"), |
| 12 | + filename: z.string().optional(), |
| 13 | + language: z.string().optional(), |
| 14 | + prompt: z.string().optional(), |
| 15 | +}) |
| 16 | + |
| 17 | +const SynthesizeBodySchema = z.object({ |
| 18 | + text: z.string().trim().min(1, "Text is required"), |
| 19 | + format: z.enum(["mp3", "wav", "opus"]).optional(), |
| 20 | +}) |
| 21 | + |
| 22 | +function getSpeechErrorStatus(error: unknown): number { |
| 23 | + if (error instanceof z.ZodError) { |
| 24 | + return 400 |
| 25 | + } |
| 26 | + if (error instanceof Error && /not configured/i.test(error.message)) { |
| 27 | + return 503 |
| 28 | + } |
| 29 | + return 502 |
| 30 | +} |
| 31 | + |
| 32 | +function getSpeechErrorMessage(error: unknown, fallback: string): string { |
| 33 | + return error instanceof Error ? error.message : fallback |
| 34 | +} |
| 35 | + |
| 36 | +export function registerSpeechRoutes(app: FastifyInstance, deps: RouteDeps) { |
| 37 | + app.get("/api/speech/capabilities", async () => deps.speechService.getCapabilities()) |
| 38 | + |
| 39 | + app.post("/api/speech/transcribe", async (request, reply) => { |
| 40 | + try { |
| 41 | + const body = TranscribeBodySchema.parse(request.body ?? {}) |
| 42 | + return await deps.speechService.transcribe(body) |
| 43 | + } catch (error) { |
| 44 | + request.log.error({ err: error }, "Failed to transcribe audio") |
| 45 | + reply.code(getSpeechErrorStatus(error)) |
| 46 | + return { error: getSpeechErrorMessage(error, "Failed to transcribe audio") } |
| 47 | + } |
| 48 | + }) |
| 49 | + |
| 50 | + app.post("/api/speech/synthesize", async (request, reply) => { |
| 51 | + try { |
| 52 | + const body = SynthesizeBodySchema.parse(request.body ?? {}) |
| 53 | + return await deps.speechService.synthesize(body) |
| 54 | + } catch (error) { |
| 55 | + request.log.error({ err: error }, "Failed to synthesize audio") |
| 56 | + reply.code(getSpeechErrorStatus(error)) |
| 57 | + return { error: getSpeechErrorMessage(error, "Failed to synthesize audio") } |
| 58 | + } |
| 59 | + }) |
| 60 | +} |
0 commit comments