Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

speech.ts

84 lines3.4 KB

1import {
2 SPEECH_MAX_OPTIONS_BYTES,
3 type SpeechCustomWords,
4 SpeechTranscriptionOptions,
5} from "@t3tools/contracts";
6import * as Schema from "effect/Schema";
7​
8const decodeOptions = Schema.decodeUnknownSync(Schema.fromJsonString(SpeechTranscriptionOptions));
9const encodeOptions = Schema.encodeSync(Schema.fromJsonString(SpeechTranscriptionOptions));
10​
11/** Resolve the language the model can produce from the requested language. */
12export function effectiveSpeechLanguage(
13 model: { readonly languages: readonly string[]; readonly supportsLanguageDetection: boolean },
14 intent: string,
15): string {
16 if (model.languages.length === 1) return model.languages[0]!;
17 if (intent !== "auto" && model.languages.includes(intent)) return intent;
18 if (model.supportsLanguageDetection) return "auto";
19 return model.languages.find((language) => language === "en") ?? model.languages[0] ?? "auto";
21​
22const vocabularyKey = (value: string) => value.trim().normalize("NFC").toLocaleLowerCase();
23​
24/**
25 * Project spellings win over personal ones. Hint terms, such as the project name or the
26 * correction cue, come first so the 100-entry wire limit cannot drop them.
27 */
28export function resolveSpeechVocabulary(input: {
29 readonly personal: SpeechCustomWords;
30 readonly project: SpeechCustomWords;
31 readonly hints?: ReadonlyArray<string>;
32}): SpeechCustomWords {
33 const known = new Set(
34 [...input.project, ...input.personal].flatMap(({ term, aliases }) =>
35 [term, ...aliases].map(vocabularyKey),
36 ),
37 );
38 // A hint that is already a dictionary entry keeps that entry and its aliases in place.
39 const hints = (input.hints ?? []).flatMap((hint) => {
40 const term = hint.replace(/\s+/g, " ").trim();
41 return term.length > 0 && term.length <= 50 && !known.has(vocabularyKey(term))
42 ? [{ term, aliases: [] }]
43 : [];
44 });
45 const seen = new Set<string>();
46 return [...hints, ...input.project, ...input.personal]
47 .flatMap(({ term, aliases }) => {
48 if (seen.has(vocabularyKey(term))) return [];
49 seen.add(vocabularyKey(term));
50 const uniqueAliases = aliases.filter((alias) => {
51 if (seen.has(vocabularyKey(alias))) return false;
52 seen.add(vocabularyKey(alias));
53 return true;
54 });
55 return [{ term, aliases: uniqueAliases }];
56 })
57 .slice(0, 100);
59​
60/** Binary requests contain a four-byte JSON length, UTF-8 options, then unencoded PCM. */
61export function encodeSpeechPcmRequest(
62 pcm: Uint8Array,
63 options: SpeechTranscriptionOptions,
64): Uint8Array<ArrayBuffer> {
65 const metadata = new TextEncoder().encode(encodeOptions(options));
66 if (metadata.byteLength > SPEECH_MAX_OPTIONS_BYTES)
67 throw new Error("Speech options are too large.");
68 const body = new Uint8Array(4 + metadata.byteLength + pcm.byteLength);
69 new DataView(body.buffer).setUint32(0, metadata.byteLength, true);
70 body.set(metadata, 4);
71 body.set(pcm, 4 + metadata.byteLength);
72 return body;
74​
75export function decodeSpeechPcmRequest(body: Uint8Array) {
76 if (body.byteLength < 4) throw new Error("Missing speech options.");
77 const length = new DataView(body.buffer, body.byteOffset, body.byteLength).getUint32(0, true);
78 if (length > SPEECH_MAX_OPTIONS_BYTES || 4 + length >= body.byteLength)
79 throw new Error("Invalid speech options length.");
80 const options = decodeOptions(
81 new TextDecoder("utf-8", { fatal: true }).decode(body.subarray(4, 4 + length)),
82 );
83 return { pcm: body.subarray(4 + length), options };