Repository navigation
feat(ai): useTranscribe and useMicrophone with 120 s chunked transcription (#523 3.3/3.4) - #628
mayankmahavar1mg wants to merge 1 commit into
Conversation
…iption (#523 3.3/3.4) Speech to text as a hook, on the device when it can, and the recorder moved out of the Pipeline lab into the library. - catalyst-ai: splitAudio / prepareAudioChunks decode a clip once and cut it into 28 s pieces at the quietest 20 ms frame before each limit (no overlap, so no repeated words). Over 120 s the result says truncated; nothing is cut silently. - useTranscribe (catalyst-core/hooks): modelled on useVision. Pieces are transcribed in order on the engine the first piece chose, silent pieces are skipped, the transcript and "part N of M" progress update as it runs, and the model is unloaded once at the end. Stops at needs-consent / denied on the first piece; approve() applies to every piece. chunkSeconds: null sends the clip whole. - Routing: Consent.pin keeps a multi-call job on one candidate. Routing re-ranks on every call, so chunks could otherwise land on different models. The privacy policy still applies to the pinned candidate. - useMicrophone (catalyst-core/hooks): MediaRecorder with live level, silence auto-stop and maxSeconds (default 120). Web only: the Android WebView grants camera but not microphone requests and the iOS shell declares no microphone usage, so a native recorder bridge is a follow-up. - Pipeline lab: the on-device speech stage uses useTranscribe and shows progress. Not covered: the native Gemma audio path and the lab's Gemini path are unchanged (no chunking); the voice-notes example page and docs are not written. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
DeputyDev has started reviewing your pull request. |
| return (result?.output ?? "").trim() | ||
| const heard = await asrRef.current.transcribe(data) | ||
| if (!heard) throw asrRef.current.lastError() ?? new Error("The recording could not be transcribed") | ||
| if (heard.truncated) console.warn(`[pipeline-lab] recording is ${heard.durationSec}s; only the first ${heard.durationSec}s were transcribed`) |
There was a problem hiding this comment.
ERROR: This warning presents heard.durationSec as the original recording length, but that value is already capped at maxSeconds. For any truncated recording, both interpolations therefore show the transcribed prefix rather than the actual source duration. Reword this as exceeding the transcription limit, or expose the uncapped duration separately.
A recording longer than 120 seconds is misleadingly reported as being exactly 120 seconds.
if (heard.truncated) console.warn(`[pipeline-lab] recording exceeded the ${heard.durationSec}s transcription limit; only the first ${heard.durationSec}s were transcribed`)
| // pushing a chunk past the truncation in toMono16k. | ||
| export const CHUNK_SECONDS = MAX_AUDIO_SECONDS - 2 | ||
| // The longest clip one transcription takes. Longer input is refused with `truncated: true`, never cut silently. | ||
| export const MAX_CLIP_SECONDS = 120 |
There was a problem hiding this comment.
DOCUMENTATION: Please update the package documentation for this new limit. The README still describes a 30-second on-device audio cap, while this API now distinguishes the per-chunk encoder limit from a 120-second chunked transcription limit and reports truncated beyond it.
Consumers cannot infer the new per-chunk versus per-recording limits from the existing README.
Document the 30-second encoder limit, the default 28-second chunks, the 120-second overall limit, and the `truncated` result.
| * to merge two overlapping transcripts, so overlap would repeat words). Pure; no decoding. | ||
| * -> [{ samples, startSec, endSec, silent }] | ||
| */ | ||
| export function splitAudio(samples, { chunkSeconds = CHUNK_SECONDS, searchSeconds = 4 } = {}) { |
There was a problem hiding this comment.
ERROR: Validate chunkSeconds before deriving limit. With chunkSeconds: 0, cut remains equal to start, so push(cut) makes no progress and this loop runs forever for non-empty input; negative values can move start backward. Because this function is exported and the option is forwarded by prepareAudioChunks, malformed runtime configuration can block the browser thread.
A non-positive chunk size creates a deterministic non-terminating public API call.
if (!Number.isFinite(chunkSeconds) || chunkSeconds <= 0) throw new RangeError("chunkSeconds must be a finite positive number")
| if (typeof dataUrl !== "string" || !dataUrl.startsWith("data:")) throw new Error("Audio must be a base64 data URL") | ||
| const { channels, sampleRate } = await decode(base64ToBytes(dataUrl.slice(dataUrl.indexOf(",") + 1))) | ||
| const fullSeconds = channels[0].length / sampleRate | ||
| const samples = toMono16k(channels, sampleRate, { maxSeconds }) |
There was a problem hiding this comment.
PERFORMANCE_OPTIMIZATION: The 120-second cap currently bounds only the resampled output. toMono16k first allocates and fills a mono buffer for the complete decoded recording, so a long file still consumes CPU and an extra Float32Array proportional to its full duration even though the tail is discarded. Limit the input frame count before downmixing.
Preprocessing memory and CPU remain proportional to the full source duration rather than the advertised transcription limit.
Downmix only `Math.min(channels[0].length, Math.ceil(maxSeconds * sampleRate))` input frames before resampling.
| export { useAI } from "./useAI.js" | ||
| export { useVision, VisionError } from "./useVision.js" | ||
| export type { UseVisionOptions, UseVisionResult, VisionStatus, VisionConsent, VisionModelState, Schema, ImageSource } from "./useVision.js" | ||
| export { useTranscribe, TranscribeError } from "./useTranscribe.js" |
There was a problem hiding this comment.
DOCUMENTATION: These hooks are now part of the public export surface, but the package README does not document how to connect recording to transcription or handle supported, permission errors, consent, denial, and truncation. Add a public usage example and the relevant browser/platform limitations.
The newly exported consumer API has behavior-critical contracts that are currently available only in source comments.
Document `useMicrophone({ onRecorded: clip => transcription.transcribe(clip) })` together with `supported`, permission failures, `needs-consent`/`approve`, denial, and the transcription limit.
| release() | ||
| }, [stop, release]) | ||
|
|
||
| const start = useCallback(async () => { |
There was a problem hiding this comment.
CODE_MAINTAINABILTIY: live.current is not assigned until after getUserMedia() resolves, so two rapid start() calls can both pass this guard and create sessions, with the later one overwriting the earlier reference. Unmount or cancellation while permission is pending has the same ownership gap: cleanup sees no session, then the continuation can start recording afterward. Track an in-flight start token, reject duplicates, and stop any stream returned for a stale or unmounted request.
Concurrent or delayed permission results can leave microphone tracks, recorders, and timers unreachable by release().
Set a pending generation before awaiting `getUserMedia`; invalidate it on cancel/unmount, and stop all returned tracks when the generation is stale or the hook is unmounted.
| } | ||
| try { | ||
| const blob = new Blob(chunks, { type: recorder.mimeType || "audio/webm" }) | ||
| onRecorded.current?.(await readAsDataUrl(blob), { seconds: secs }) |
There was a problem hiding this comment.
CODE_MAINTAINABILTIY: The mounted/discard check occurs before await readAsDataUrl(blob). If the hook unmounts or the operation is canceled while FileReader is pending, this callback still delivers the completed microphone clip to the stale consumer. Re-check lifecycle state after the await using a cancellation token that remains valid after release().
Recorded audio can be delivered for processing after the hook's lifecycle has ended.
const dataUrl = await readAsDataUrl(blob)
if (!mounted.current || token !== generation.current) return
onRecorded.current?.(dataUrl, { seconds: secs })
| setError(err?.name === "NotAllowedError" ? "Microphone permission was denied." : `Could not open the microphone: ${err?.message || err}`) | ||
| return | ||
| } | ||
| const mimeType = MIME_TYPES.find((t) => MediaRecorder.isTypeSupported?.(t)) |
There was a problem hiding this comment.
CODE_MAINTAINABILTIY: After the stream is acquired, recorder construction, audio-context setup, and recorder.start() are outside an error-cleanup path. A thrown setup/start error can leave tracks, a context, or the installed timer active without setting the hook's error; asynchronous recorder failures also have no handler. Route all of these failures through one cleanup path.
Browser API failures after permission succeeds can leak an active microphone session and leave hook state inconsistent.
Wrap recorder/context setup and `recorder.start()` in a cleanup-aware try/catch, and attach `recorder.onerror` to release the session and set a meaningful error.
| lastLoud: number | ||
| } | ||
|
|
||
| export function useMicrophone(options: UseMicrophoneOptions = {}): UseMicrophoneResult { |
There was a problem hiding this comment.
CODE_MAINTAINABILTIY: Pipeline Lab still uses its local useVoiceRecorder, which independently implements the same MediaRecorder, AudioContext, RMS, silence timeout, and cleanup lifecycle as this new shared hook. Migrate that consumer to useMicrophone or reduce the local hook to a compatibility wrapper so recorder fixes do not diverge.
Two full recorder implementations must now receive the same permission, cleanup, and option-handling fixes independently.
Replace the Pipeline Lab `useVoiceRecorder` usage with `useMicrophone`, then remove the local implementation or delegate it to the shared hook.
| lastLoud: number | ||
| } | ||
|
|
||
| export function useMicrophone(options: UseMicrophoneOptions = {}): UseMicrophoneResult { |
There was a problem hiding this comment.
DOCUMENTATION: Add declaration-level JSDoc to this newly exported hook. The current // block is detached from the symbol, so generated API/IDE documentation will not expose its web-only limitation or the contracts around supported, permission errors, onRecorded, stop, and cancel.
The public symbol omits behavior and platform constraints that consumers need when invoking it.
/** Records microphone input in a supported browser and delivers a data URL through `onRecorded`. Check `supported`, handle permission errors, and use `stop()` or `cancel()` to finish or discard the clip. */
| let pieces: { data: string; silent: boolean }[] | ||
| let durationSec = 0 | ||
| let truncated = false | ||
| if (chunkSeconds === null) { |
There was a problem hiding this comment.
SECURITY: A Blob can finish blobToDataUrl after this request was canceled or superseded. The chunked branch checks requestId after preparation, but this whole-recording branch has no equivalent check before generate, so stale audio is still submitted. Check the request ID immediately after source conversion and before selecting either branch.
Cancellation or a newer transcription does not prevent an older whole-recording Blob from reaching the model.
if (id !== requestId.current) return null
| let pieces: { data: string; silent: boolean }[] | ||
| let durationSec = 0 | ||
| let truncated = false | ||
| if (chunkSeconds === null) { |
There was a problem hiding this comment.
ERROR: Whole-recording mode bypasses prepareAudioChunks, so maxSeconds is not enforced and the source is sent as one unbounded piece, while durationSec and truncated remain at their 0/false defaults. This contradicts the public option and result contracts. Either enforce and populate those fields in this branch, or explicitly document whole-recording mode as unlimited and exempt from that metadata guarantee.
A real whole-clip transcription can return false duration metadata and submit input beyond the documented maximum.
Apply duration/maxSeconds handling before constructing the whole-recording piece and assign `durationSec`/`truncated`; otherwise revise the option and result documentation to define this mode as uncapped.
|
DeputyDev has completed a review of your pull request for commit b561603. |
Stacked on #621 (base
feature/ai-21-live-voice). Part of #523 (audio track 3.3 and 3.4), related to #611.What
splitAudioandprepareAudioChunksdecode a clip once and cut it into 28 s pieces at the quietest 20 ms frame before each limit, so a word is rarely split. Pieces do not overlap (a speech model cannot merge overlapping transcripts, so overlap would repeat words). A clip over 120 s comes back withtruncated: true; nothing is cut silently.useTranscribe(catalyst-core/hooks, modelled onuseVision):needs-consent/deniedon the first piece;approve()applies to every piecechunkSeconds: nullsends the clip whole (for a cloud model that takes long audio)Consent.pinkeeps a multi-call job on one candidate. Auto routing re-ranks on every call (observed speed, loaded model), so chunks of one recording could otherwise land on different models. The privacy policy still applies to the pinned candidate.useMicrophone(catalyst-core/hooks): the recorder moved out of the Pipeline lab. MediaRecorder, live level, silence auto-stop,maxSeconds(default 120),supportedflag.useTranscribeand shows progress.Verification
useTranscribeanduseMicrophone); catalyst-ai: 319 pass (5 new for the splitter);tscdeclarations clean.Not verified / limits
useMicrophoneis web only: the Android WebView only grants camera permission requests and the iOS shell declares no microphone usage. A native recorder bridge is a follow-up.🤖 Generated with Claude Code
DeputyDev generated PR summary:
Size XL: This PR changes include 904 lines and should take approximately 3-6 hours to review
This PR adds a reusable browser microphone and long-form transcription flow.
Main changes
Adds
useMicrophoneMediaRecorderandgetUserMedia.start,stop, andcancel.Adds
useTranscribeBlob, orFile.truncated: true.Improves routing consistency
needs-consentordeniedstates, withapprove()available to retry using the requested consent.Updates
PipelineLabuseAI().generate()call withuseTranscribe.Adds tests
In short, the PR changes transcription from a single short audio request into a consent-aware, chunked voice-recording pipeline that can process up to two minutes of audio on supported devices.
DeputyDev generated PR summary until b561603