peppa/packages/testkit/src/mock-transcribe.ts
Асель db822a570c PEP-45: stories from a Telegram message (text or voice); docs; archive PEP-44/45/46 changes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 06:07:18 +05:00

52 lines
2.6 KiB
TypeScript

// Mock OpenAI-compatible speech-to-text (PEP-45): POST /v1/audio/transcriptions, multipart
// `file` + `model` (+ `language`, `response_format`), Bearer key → {"text": "…"}, errors as
// {"error": {"message"}} with 400/401 like OpenAI. "Speech" is the audio bytes as UTF-8
// prefixed "MOCK-SPEECH:"; anything else transcribes to "" (silence).
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
export class MockTranscribe {
readonly key = "mock-transcribe-key";
readonly requests: Array<{ model: string; language: string | null; filename: string; bytes: number }> = [];
private server: Server | null = null;
url = "";
/** Audio that the mock "hears" as `text`. */
static speech(text: string): Buffer {
return Buffer.from(`MOCK-SPEECH:${text}`, "utf8");
}
async start(port = 0): Promise<this> {
this.server = createServer(async (req, res) => {
const send = (status: number, body: unknown) => {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
};
if (req.method !== "POST" || req.url !== "/v1/audio/transcriptions") return send(404, { error: { message: "not found" } });
if (req.headers.authorization !== `Bearer ${this.key}`) return send(401, { error: { message: "Incorrect API key provided" } });
const chunks: Buffer[] = [];
for await (const c of req) chunks.push(c as Buffer);
let form: FormData;
try {
form = await new Request("http://x", { method: "POST", headers: { "content-type": String(req.headers["content-type"]) }, body: Buffer.concat(chunks) }).formData();
} catch {
return send(400, { error: { message: "Could not parse multipart form" } });
}
const file = form.get("file");
const model = form.get("model");
if (!(file instanceof Blob) || typeof model !== "string" || !model) return send(400, { error: { message: "file and model are required" } });
const bytes = Buffer.from(await file.arrayBuffer());
this.requests.push({ model, language: (form.get("language") as string | null) ?? null, filename: (file as File).name ?? "", bytes: bytes.length });
const s = bytes.toString("utf8");
send(200, { text: s.startsWith("MOCK-SPEECH:") ? s.slice("MOCK-SPEECH:".length) : "" });
});
await new Promise<void>((r) => this.server!.listen(port, "127.0.0.1", r));
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}/v1`;
return this;
}
async stop() {
await new Promise<void>((r) => this.server?.close(() => r()) ?? r());
}
}