@chai-ui/core 0.7.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/composer-view.d.ts +35 -6
- package/dist/composer-view.d.ts.map +1 -1
- package/dist/composer-view.js +50 -6
- package/dist/composer-view.js.map +1 -1
- package/dist/composer.d.ts +15 -6
- package/dist/composer.d.ts.map +1 -1
- package/dist/composer.js +24 -4
- package/dist/composer.js.map +1 -1
- package/dist/engine.d.ts +4 -0
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js.map +1 -1
- package/dist/engines/fal.d.ts +25 -0
- package/dist/engines/fal.d.ts.map +1 -1
- package/dist/engines/fal.js +41 -0
- package/dist/engines/fal.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/model-routing.d.ts +2 -2
- package/dist/model-routing.d.ts.map +1 -1
- package/dist/run.d.ts +4 -4
- package/dist/run.d.ts.map +1 -1
- package/dist/run.js +2 -2
- package/dist/run.js.map +1 -1
- package/dist/suggested-models.d.ts.map +1 -1
- package/dist/suggested-models.js +2 -1
- package/dist/suggested-models.js.map +1 -1
- package/dist/types.d.ts +12 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/voice-input.d.ts +79 -0
- package/dist/voice-input.d.ts.map +1 -0
- package/dist/voice-input.js +207 -0
- package/dist/voice-input.js.map +1 -0
- package/package.json +1 -1
- package/src/composer-view.ts +68 -9
- package/src/composer.ts +36 -9
- package/src/engine.ts +4 -0
- package/src/engines/fal.ts +55 -0
- package/src/index.ts +1 -0
- package/src/model-routing.ts +2 -2
- package/src/run.ts +4 -4
- package/src/suggested-models.ts +2 -1
- package/src/types.ts +13 -0
- package/src/voice-input.ts +257 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Voice input for the Composer: record from the microphone, send the clip
|
|
3
|
+
* to a speech-to-text model, and hand back the transcript. Framework-free,
|
|
4
|
+
* so React and Vue each add only the button.
|
|
5
|
+
*/
|
|
6
|
+
import { abortError, isAbortError } from "./engine.js";
|
|
7
|
+
import { createFalTranscriber } from "./engines/fal.js";
|
|
8
|
+
|
|
9
|
+
/** A recorded clip, as a data URL. */
|
|
10
|
+
export interface VoiceClip {
|
|
11
|
+
src: string;
|
|
12
|
+
kind: "audio";
|
|
13
|
+
/** What the browser recorded, e.g. `"audio/webm;codecs=opus"` (Chrome, Firefox) or `"audio/mp4"` (Safari). */
|
|
14
|
+
mimeType: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Turns a recorded clip into text. Reject with an `AbortError` when `signal` aborts. */
|
|
18
|
+
export type Transcribe = (audio: VoiceClip, options?: { signal?: AbortSignal }) => Promise<string>;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Turns on the Composer's mic. Name a Fal speech-to-text model and Chai
|
|
22
|
+
* sends the clip through your existing `/api/chai/fal` route, or pass your
|
|
23
|
+
* own `transcribe` for any other provider. There's no default model: the
|
|
24
|
+
* mic shows only once you choose one.
|
|
25
|
+
*/
|
|
26
|
+
export type VoiceInputConfig = (
|
|
27
|
+
| { model: string; transcribe?: never; endpoint?: string }
|
|
28
|
+
| { transcribe: Transcribe; model?: never; endpoint?: never }
|
|
29
|
+
) & {
|
|
30
|
+
/** Longest recording, in seconds. Recording stops and transcribes at this length. Defaults to 60. */
|
|
31
|
+
maxSeconds?: number;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type VoiceInputStatus = "idle" | "recording" | "transcribing" | "error";
|
|
35
|
+
|
|
36
|
+
export interface VoiceInputState {
|
|
37
|
+
status: VoiceInputStatus;
|
|
38
|
+
/** How long the current recording has run. */
|
|
39
|
+
elapsedMs: number;
|
|
40
|
+
/** A short message for the person while `status` is "error". */
|
|
41
|
+
error: string | null;
|
|
42
|
+
/**
|
|
43
|
+
* The microphone's recent loudness while recording, oldest first, each
|
|
44
|
+
* 0–1: what a waveform draws, so the person sees they're being heard.
|
|
45
|
+
* Empty when not recording, or when the browser has no Web Audio.
|
|
46
|
+
*/
|
|
47
|
+
levels: number[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** How many level readings a waveform shows. */
|
|
51
|
+
export const VOICE_LEVEL_COUNT = 48;
|
|
52
|
+
|
|
53
|
+
export const DEFAULT_VOICE_MAX_SECONDS = 60;
|
|
54
|
+
|
|
55
|
+
/** Recording formats, best first. Chrome and Firefox record WebM, Safari MP4. */
|
|
56
|
+
const MIME_TYPES = ["audio/webm;codecs=opus", "audio/webm", "audio/mp4", "audio/ogg;codecs=opus"];
|
|
57
|
+
|
|
58
|
+
/** The `Transcribe` a config describes: its own, or a Fal transcriber for its model. */
|
|
59
|
+
export function voiceTranscriber(config: VoiceInputConfig): Transcribe {
|
|
60
|
+
return config.transcribe ?? createFalTranscriber({ model: config.model!, endpoint: config.endpoint });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** "0:05", "1:00": how long a recording has run. */
|
|
64
|
+
export function formatVoiceElapsed(ms: number): string {
|
|
65
|
+
const s = Math.floor(ms / 1000);
|
|
66
|
+
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Why the microphone couldn't start, in words for the person. */
|
|
70
|
+
export function describeMicError(err: unknown): string {
|
|
71
|
+
const { name, message } = (err as { name?: string; message?: string } | null) ?? {};
|
|
72
|
+
// Chrome's wording when the computer, not the site, blocks the browser
|
|
73
|
+
// (macOS Privacy & Security, Windows microphone privacy).
|
|
74
|
+
if (name === "NotAllowedError" && /system/i.test(message ?? "")) {
|
|
75
|
+
return "Your computer is blocking this browser from the microphone. Allow it in your system's privacy settings, then reload.";
|
|
76
|
+
}
|
|
77
|
+
if (name === "NotAllowedError" || name === "SecurityError") {
|
|
78
|
+
return "Microphone access is blocked. Allow it in your browser's site settings to use voice input.";
|
|
79
|
+
}
|
|
80
|
+
if (name === "NotFoundError" || name === "OverconstrainedError") return "No microphone found.";
|
|
81
|
+
if (name === "NotReadableError") return "The microphone is in use by another app.";
|
|
82
|
+
return "The microphone couldn't start.";
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface VoiceInputDeps {
|
|
86
|
+
/** Defaults to the browser's `navigator.mediaDevices.getUserMedia`. */
|
|
87
|
+
getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;
|
|
88
|
+
/** Defaults to the browser's `MediaRecorder`. */
|
|
89
|
+
MediaRecorder?: typeof MediaRecorder;
|
|
90
|
+
/** Defaults to the browser's `AudioContext`, for the waveform. Without one, recording still works. */
|
|
91
|
+
AudioContext?: typeof AudioContext;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The recorder behind the mic button. `start` asks for the microphone and
|
|
96
|
+
* records; `stop` ends the recording and transcribes it; `cancel` stops
|
|
97
|
+
* either without a transcript. `onTranscript` gets the text: it never
|
|
98
|
+
* submits, so the person can fix it first.
|
|
99
|
+
*/
|
|
100
|
+
export function createVoiceInput(
|
|
101
|
+
getConfig: () => VoiceInputConfig,
|
|
102
|
+
onTranscript: (text: string) => void,
|
|
103
|
+
deps: VoiceInputDeps = {}
|
|
104
|
+
) {
|
|
105
|
+
let state: VoiceInputState = { status: "idle", elapsedMs: 0, error: null, levels: [] };
|
|
106
|
+
const listeners = new Set<() => void>();
|
|
107
|
+
const set = (next: Partial<VoiceInputState>) => {
|
|
108
|
+
state = { ...state, ...next };
|
|
109
|
+
listeners.forEach((l) => l());
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
let recorder: MediaRecorder | null = null;
|
|
113
|
+
let stream: MediaStream | null = null;
|
|
114
|
+
let timer: ReturnType<typeof setInterval> | null = null;
|
|
115
|
+
let controller: AbortController | null = null;
|
|
116
|
+
let discard = false;
|
|
117
|
+
let audio: AudioContext | null = null;
|
|
118
|
+
let readLevel: (() => number) | null = null;
|
|
119
|
+
|
|
120
|
+
function release() {
|
|
121
|
+
if (timer) clearInterval(timer);
|
|
122
|
+
timer = null;
|
|
123
|
+
void audio?.close().catch(() => {});
|
|
124
|
+
audio = null;
|
|
125
|
+
readLevel = null;
|
|
126
|
+
stream?.getTracks().forEach((t) => t.stop());
|
|
127
|
+
stream = null;
|
|
128
|
+
recorder = null;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
async function start() {
|
|
132
|
+
if (state.status === "recording" || state.status === "transcribing") return;
|
|
133
|
+
const Recorder = deps.MediaRecorder ?? (typeof MediaRecorder === "undefined" ? undefined : MediaRecorder);
|
|
134
|
+
const getUserMedia =
|
|
135
|
+
deps.getUserMedia ?? (typeof navigator !== "undefined" ? navigator.mediaDevices?.getUserMedia?.bind(navigator.mediaDevices) : undefined);
|
|
136
|
+
if (!Recorder || !getUserMedia) return set({ status: "error", error: "Voice input isn't supported in this browser." });
|
|
137
|
+
try {
|
|
138
|
+
stream = await getUserMedia({ audio: true });
|
|
139
|
+
} catch (err) {
|
|
140
|
+
return set({ status: "error", error: describeMicError(err) });
|
|
141
|
+
}
|
|
142
|
+
const mimeType = MIME_TYPES.find((t) => Recorder.isTypeSupported?.(t));
|
|
143
|
+
const chunks: Blob[] = [];
|
|
144
|
+
discard = false;
|
|
145
|
+
recorder = new Recorder(stream, mimeType ? { mimeType } : undefined);
|
|
146
|
+
recorder.ondataavailable = (e) => {
|
|
147
|
+
if (e.data.size > 0) chunks.push(e.data);
|
|
148
|
+
};
|
|
149
|
+
recorder.onstop = () => {
|
|
150
|
+
const type = recorder?.mimeType || mimeType || "audio/webm";
|
|
151
|
+
release();
|
|
152
|
+
if (discard) return set({ status: "idle", elapsedMs: 0, levels: [] });
|
|
153
|
+
void transcribe(new Blob(chunks, { type }), type);
|
|
154
|
+
};
|
|
155
|
+
recorder.start();
|
|
156
|
+
readLevel = listen(stream);
|
|
157
|
+
const startedAt = Date.now();
|
|
158
|
+
const maxMs = (getConfig().maxSeconds ?? DEFAULT_VOICE_MAX_SECONDS) * 1000;
|
|
159
|
+
set({ status: "recording", elapsedMs: 0, error: null, levels: [] });
|
|
160
|
+
timer = setInterval(() => {
|
|
161
|
+
const elapsedMs = Date.now() - startedAt;
|
|
162
|
+
const levels = readLevel ? [...state.levels, readLevel()].slice(-VOICE_LEVEL_COUNT) : state.levels;
|
|
163
|
+
set({ elapsedMs, levels });
|
|
164
|
+
if (elapsedMs >= maxMs) stop();
|
|
165
|
+
}, 80);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Reads the stream's loudness, 0–1, through Web Audio. Null without it. */
|
|
169
|
+
function listen(source: MediaStream): (() => number) | null {
|
|
170
|
+
const Context = deps.AudioContext ?? (typeof AudioContext === "undefined" ? undefined : AudioContext);
|
|
171
|
+
if (!Context) return null;
|
|
172
|
+
try {
|
|
173
|
+
audio = new Context();
|
|
174
|
+
const analyser = audio.createAnalyser();
|
|
175
|
+
analyser.fftSize = 256;
|
|
176
|
+
audio.createMediaStreamSource(source).connect(analyser);
|
|
177
|
+
const samples = new Uint8Array(analyser.fftSize);
|
|
178
|
+
return () => {
|
|
179
|
+
analyser.getByteTimeDomainData(samples);
|
|
180
|
+
let sum = 0;
|
|
181
|
+
for (const v of samples) sum += ((v - 128) / 128) ** 2;
|
|
182
|
+
// Speech sits low on this scale: lift it so a normal voice fills the bars.
|
|
183
|
+
return Math.min(1, Math.sqrt(sum / samples.length) * 4);
|
|
184
|
+
};
|
|
185
|
+
} catch {
|
|
186
|
+
return null;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async function transcribe(blob: Blob, mimeType: string) {
|
|
191
|
+
if (blob.size === 0) return set({ status: "error", error: "Nothing was recorded. Try again." });
|
|
192
|
+
set({ status: "transcribing", levels: [] });
|
|
193
|
+
controller = new AbortController();
|
|
194
|
+
try {
|
|
195
|
+
const src = await readAsDataUrl(blob);
|
|
196
|
+
if (controller.signal.aborted) throw abortError();
|
|
197
|
+
const text = (await voiceTranscriber(getConfig())({ src, kind: "audio", mimeType }, { signal: controller.signal })).trim();
|
|
198
|
+
if (!text) return set({ status: "error", error: "Didn't catch that. Try again." });
|
|
199
|
+
onTranscript(text);
|
|
200
|
+
set({ status: "idle", elapsedMs: 0, levels: [] });
|
|
201
|
+
} catch (err) {
|
|
202
|
+
if (isAbortError(err)) return set({ status: "idle", elapsedMs: 0, levels: [] });
|
|
203
|
+
set({ status: "error", error: "Transcription failed. Try again." });
|
|
204
|
+
} finally {
|
|
205
|
+
controller = null;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/** Ends the recording and transcribes it. */
|
|
210
|
+
function stop() {
|
|
211
|
+
if (recorder && recorder.state !== "inactive") recorder.stop();
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Stops recording or transcribing, with no transcript. */
|
|
215
|
+
function cancel() {
|
|
216
|
+
if (state.status === "recording") {
|
|
217
|
+
discard = true;
|
|
218
|
+
stop();
|
|
219
|
+
} else if (state.status === "transcribing") controller?.abort();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Clears an error, back to the idle mic. */
|
|
223
|
+
function dismiss() {
|
|
224
|
+
if (state.status === "error") set({ status: "idle", error: null, elapsedMs: 0, levels: [] });
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return {
|
|
228
|
+
getState: () => state,
|
|
229
|
+
subscribe(listener: () => void) {
|
|
230
|
+
listeners.add(listener);
|
|
231
|
+
return () => listeners.delete(listener);
|
|
232
|
+
},
|
|
233
|
+
start,
|
|
234
|
+
stop,
|
|
235
|
+
cancel,
|
|
236
|
+
dismiss,
|
|
237
|
+
/** Stops everything, for when the Composer goes away. */
|
|
238
|
+
dispose() {
|
|
239
|
+
discard = true;
|
|
240
|
+
controller?.abort();
|
|
241
|
+
if (recorder && recorder.state !== "inactive") recorder.stop();
|
|
242
|
+
release();
|
|
243
|
+
},
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export type VoiceInput = ReturnType<typeof createVoiceInput>;
|
|
248
|
+
|
|
249
|
+
/** A clip's data URL, for the model's `audio_url`. */
|
|
250
|
+
function readAsDataUrl(blob: Blob): Promise<string> {
|
|
251
|
+
return new Promise((resolve, reject) => {
|
|
252
|
+
const reader = new FileReader();
|
|
253
|
+
reader.onload = () => resolve(String(reader.result));
|
|
254
|
+
reader.onerror = () => reject(reader.error);
|
|
255
|
+
reader.readAsDataURL(blob);
|
|
256
|
+
});
|
|
257
|
+
}
|