Spaces:
Sleeping
Sleeping
File size: 9,870 Bytes
0e14acb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 | import { useCallback, useEffect, useRef } from "react";
import { useAudioPlayback } from "./useAudioPlayback";
interface StreamCallbacks {
workletPath: string;
onUserTranscript?: (text: string) => void;
onTranscript?: (text: string, full: string) => void;
onComplete?: (transcript: string) => void;
onError?: (error: Error) => void;
}
type TypedVoiceStreamEvent =
| { type: "user_transcript"; data: string }
| { type: "transcript"; data: string }
| { type: "audio"; data: string }
| { type: "error"; error: string };
type DoneEvent = { done: true };
type VoiceStreamEvent = TypedVoiceStreamEvent | DoneEvent;
type PlaybackHandle = ReturnType<typeof useAudioPlayback>;
type StreamState = {
fullTranscript: string;
didComplete: boolean;
};
const SSE_EVENT_DELIMITER = /\r\n\r\n|\n\n|\r\r/g;
function createAbortError(): Error {
const error = new Error("The operation was aborted");
error.name = "AbortError";
return error;
}
function toError(error: unknown): Error {
if (error instanceof Error) return error;
return new Error(typeof error === "string" ? error : "Unknown error");
}
function notifyError(callbacks: Pick<StreamCallbacks, "onError">, error: Error) {
try {
callbacks.onError?.(error);
} catch {
// Do not let onError mask the original error.
}
}
function isVoiceStreamEvent(value: unknown): value is VoiceStreamEvent {
if (!value || typeof value !== "object") return false;
const record = value as Record<string, unknown>;
if (record.done === true) return true;
switch (record.type) {
case "user_transcript":
case "transcript":
case "audio":
return typeof record.data === "string";
case "error":
return typeof record.error === "string";
default:
return false;
}
}
function parseVoiceStreamEvent(raw: string): VoiceStreamEvent {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
throw new Error("Received malformed SSE JSON payload");
}
if (!isVoiceStreamEvent(parsed)) {
throw new Error("Received unexpected SSE event shape");
}
return parsed;
}
function readSseDataFromBlock(block: string): string | null {
const normalizedBlock = block.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
const dataLines: string[] = [];
for (const line of normalizedBlock.split("\n")) {
if (!line.startsWith("data:")) {
continue;
}
// SSE allows one optional leading space after the colon.
dataLines.push(line.slice(5).replace(/^ /, ""));
}
if (dataLines.length === 0) {
return null;
}
return dataLines.join("\n");
}
function extractCompleteSseBlocks(buffer: string): {
blocks: string[];
remaining: string;
} {
const blocks: string[] = [];
let lastIndex = 0;
SSE_EVENT_DELIMITER.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = SSE_EVENT_DELIMITER.exec(buffer)) !== null) {
blocks.push(buffer.slice(lastIndex, match.index));
lastIndex = match.index + match[0].length;
}
return {
blocks,
remaining: buffer.slice(lastIndex),
};
}
function isDoneEvent(event: VoiceStreamEvent): event is DoneEvent {
return "done" in event && (event as DoneEvent).done === true;
}
function handleVoiceStreamEvent(
event: VoiceStreamEvent,
playback: PlaybackHandle,
callbacks: Omit<StreamCallbacks, "workletPath">,
state: StreamState
) {
if (isDoneEvent(event)) {
if (!state.didComplete) {
state.didComplete = true;
playback.signalComplete();
callbacks.onComplete?.(state.fullTranscript);
}
return;
}
switch (event.type) {
case "user_transcript":
callbacks.onUserTranscript?.(event.data);
return;
case "transcript":
state.fullTranscript += event.data;
callbacks.onTranscript?.(event.data, state.fullTranscript);
return;
case "audio":
playback.pushAudio(event.data);
return;
case "error":
throw new Error(event.error);
}
}
async function blobToBase64(blob: Blob, signal?: AbortSignal): Promise<string> {
if (signal?.aborted) {
throw createAbortError();
}
return new Promise<string>((resolve, reject) => {
const reader = new FileReader();
const cleanup = () => {
signal?.removeEventListener("abort", onAbort);
reader.onload = null;
reader.onerror = null;
reader.onabort = null;
};
const onAbort = () => {
cleanup();
try {
reader.abort();
} catch {
// Ignore abort races if the read already finished.
}
reject(createAbortError());
};
signal?.addEventListener("abort", onAbort, { once: true });
reader.onload = () => {
const result = reader.result;
cleanup();
if (typeof result !== "string") {
reject(new Error("Failed to read audio blob"));
return;
}
const commaIndex = result.indexOf(",");
if (commaIndex === -1) {
reject(new Error("Failed to parse audio data URL"));
return;
}
resolve(result.slice(commaIndex + 1));
};
reader.onerror = () => {
const error = reader.error ?? new Error("Failed to read audio blob");
cleanup();
reject(error);
};
reader.onabort = () => {
cleanup();
reject(createAbortError());
};
reader.readAsDataURL(blob);
});
}
async function readErrorText(response: Response): Promise<string> {
try {
return (await response.text()).trim();
} catch {
return "";
}
}
export function useVoiceStream({ workletPath, ...callbacks }: StreamCallbacks) {
const playback = useAudioPlayback(workletPath);
const callbacksRef = useRef<Omit<StreamCallbacks, "workletPath">>(callbacks);
callbacksRef.current = callbacks;
const playbackRef = useRef<PlaybackHandle>(playback);
playbackRef.current = playback;
const activeRequestRef = useRef<AbortController | null>(null);
useEffect(() => {
return () => {
activeRequestRef.current?.abort();
};
}, []);
const streamVoiceResponse = useCallback(
async (url: string, audioBlob: Blob): Promise<void> => {
activeRequestRef.current?.abort();
const abortController = new AbortController();
activeRequestRef.current = abortController;
const throwIfNotCurrent = () => {
if (
abortController.signal.aborted ||
activeRequestRef.current !== abortController
) {
throw createAbortError();
}
};
const processBlocks = (blocks: string[], state: StreamState) => {
for (const block of blocks) {
throwIfNotCurrent();
const rawData = readSseDataFromBlock(block);
if (!rawData) {
continue;
}
const event = parseVoiceStreamEvent(rawData);
handleVoiceStreamEvent(
event,
playbackRef.current,
callbacksRef.current,
state
);
}
};
const state: StreamState = {
fullTranscript: "",
didComplete: false,
};
try {
await playbackRef.current.init();
throwIfNotCurrent();
playbackRef.current.clear();
const base64Audio = await blobToBase64(audioBlob, abortController.signal);
throwIfNotCurrent();
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "text/event-stream",
},
body: JSON.stringify({ audio: base64Audio }),
signal: abortController.signal,
});
throwIfNotCurrent();
if (!response.ok) {
const detail = await readErrorText(response);
throw new Error(
detail
? `Voice request failed (${response.status} ${response.statusText}): ${detail}`
: `Voice request failed (${response.status} ${response.statusText})`
);
}
if (!response.body) {
throw new Error("Voice request failed: response body is missing");
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
try {
while (true) {
const { done, value } = await reader.read();
throwIfNotCurrent();
if (done) {
break;
}
buffer += decoder.decode(value, { stream: true });
const { blocks, remaining } = extractCompleteSseBlocks(buffer);
buffer = remaining;
processBlocks(blocks, state);
}
// Flush any trailing UTF-8 bytes.
buffer += decoder.decode();
const { blocks, remaining } = extractCompleteSseBlocks(buffer);
processBlocks(blocks, state);
// Process a final unterminated event if the server closed without a trailing blank line.
const finalData = readSseDataFromBlock(remaining);
if (finalData) {
throwIfNotCurrent();
const event = parseVoiceStreamEvent(finalData);
handleVoiceStreamEvent(
event,
playbackRef.current,
callbacksRef.current,
state
);
}
} finally {
try {
await reader.cancel();
} catch {
// Ignore cleanup errors.
}
reader.releaseLock();
}
} catch (error) {
const err = toError(error);
if (err.name === "AbortError") {
return;
}
notifyError(callbacksRef.current, err);
throw err;
} finally {
if (activeRequestRef.current === abortController) {
activeRequestRef.current = null;
}
}
},
[]
);
return { streamVoiceResponse, playbackState: playback.state };
} |