Spaces:
Running on Zero
Running on Zero
Download src/speech.js from fffiloni/cabin-local: direct link, hf CLI and curl.
- Browser
- Download file 6.66 kB
-
https://huggingface.co/spaces/fffiloni/cabin-local/resolve/main/src/speech.js
- Command line
-
hf download hf://spaces/fffiloni/cabin-local/src/speech.js
-
curl -L -o speech.js https://huggingface.co/spaces/fffiloni/cabin-local/resolve/main/src/speech.js
6.66 kB
| import { Client, handle_file } from '@gradio/client'; | |
| export class ServerSpeech { | |
| constructor(){this.client=null;this.pending=null;this.config=null;this.generation=0;} | |
| async connect(){ | |
| if(this.client)return; | |
| const r=await fetch('/voice-config.json');if(!r.ok)throw Error('The voice server is unavailable. Try again shortly.'); | |
| this.config=await r.json();if(this.config.mode!=='zerogpu')throw Error('Interface preview only. Server speech is disabled.'); | |
| this.client=await Client.connect(`${location.origin}${this.config.apiPath}`,{record_history:false,events:['data','status']}); | |
| } | |
| async run(endpoint,data,onStatus,generation=this.generation){ | |
| const active=()=>{if(generation!==this.generation)throw new DOMException('Speech stopped','AbortError');}; | |
| active();await this.connect();active(); | |
| const job=this.client.submit(endpoint,data);this.pending=job; | |
| let result; | |
| try{ | |
| for await(const event of job){ | |
| active(); | |
| if(event.type==='data')result=event.data; | |
| if(event.type==='status'){ | |
| if(event.stage==='error'){ | |
| const message=event.message||'The speech server could not finish.'; | |
| throw Error(/ZeroGPU.*(quota|runs limit)|exceeded.*ZeroGPU/i.test(message)?'ZeroGPU quota reached. Try again later.':message); | |
| } | |
| onStatus?.(event.stage==='pending'?'Waiting for ZeroGPU…':'Processing speech on ZeroGPU…'); | |
| } | |
| } | |
| active();if(!result)throw Error('No result received from the speech server.'); | |
| return result[0]; | |
| }finally{if(this.pending===job)this.pending=null;} | |
| } | |
| async transcribe(blob,onStatus){ | |
| // Materialize the short clip before upload: a file picker may relinquish | |
| // its disk-backed handle when the input is cleared for the next recording. | |
| const generation=this.generation; | |
| const audio=new File([await blob.arrayBuffer()],blob.name||'question.wav',{type:blob.type||'audio/wav'}); | |
| return this.run('/transcribe',{audio:handle_file(audio)},onStatus,generation); | |
| } | |
| async synthesize(text,voice,onStatus){ | |
| const file=await this.run('/synthesize',{text,voice},onStatus); | |
| if(!file?.url)throw Error('The server returned no audio file.'); | |
| const url=new URL(file.url,location.origin); | |
| if(url.origin!==location.origin)throw Error('Unexpected audio host.'); | |
| return url.href; | |
| } | |
| cancel(){this.generation++;this.pending?.cancel().catch(()=>{});this.pending=null;} | |
| } | |
| // Bounded PCM capture. Silence detection ends the turn without adding a | |
| // second in-car button: the Swift recognizer also ends after a pause. | |
| export class Microphone { | |
| constructor(){this.session=null;} | |
| get active(){return this.session!==null;} | |
| async record(onLevel){ | |
| if(!navigator.mediaDevices?.getUserMedia)throw Error('This browser cannot record audio. Use the text test below.'); | |
| this.cancel(); | |
| // Every async continuation owns its resources. A late permission result | |
| // must never close the microphone or audio context of a newer recording. | |
| const session={cancelled:false};this.session=session; | |
| const active=()=>{if(session.cancelled||this.session!==session)throw new DOMException('Recording stopped','AbortError');}; | |
| try{ | |
| session.stream=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:true,noiseSuppression:true}});active(); | |
| session.context=new AudioContext();await session.context.resume();active(); | |
| session.source=session.context.createMediaStreamSource(session.stream); | |
| session.processor=session.context.createScriptProcessor(4096,1,1); | |
| session.source.connect(session.processor);session.processor.connect(session.context.destination); | |
| const rate=session.context.sampleRate;const chunks=[];let samples=0,speech=false,lastVoice=performance.now(),started=lastVoice; | |
| const pcm=await new Promise((resolve,reject)=>{ | |
| session.reject=reject; | |
| const finish=()=>{if(session.cancelled||this.session!==session)return;session.reject=null;resolve(chunks);}; | |
| session.processor.onaudioprocess=event=>{ | |
| if(session.cancelled||this.session!==session)return; | |
| const data=event.inputBuffer.getChannelData(0);chunks.push(new Float32Array(data));samples+=data.length; | |
| const rms=Math.sqrt(data.reduce((sum,v)=>sum+v*v,0)/data.length);onLevel?.(Math.min(1,rms*12)); | |
| const now=performance.now();if(rms>0.012){speech=true;lastVoice=now;} | |
| if(samples>=rate*20||(speech&&now-lastVoice>1500&&now-started>700))finish(); | |
| }; | |
| session.timer=setTimeout(finish,20500); | |
| }); | |
| active();this.cleanup(session); | |
| if(!speech)throw Error('No speech detected. Tap Talk and try again.'); | |
| const length=pcm.reduce((n,c)=>n+c.length,0);const merged=new Float32Array(length);let offset=0;for(const c of pcm){merged.set(c,offset);offset+=c.length;} | |
| const offline=new OfflineAudioContext(1,Math.ceil(length*16000/rate),16000);const buffer=offline.createBuffer(1,length,rate);buffer.copyToChannel(merged,0); | |
| const source=offline.createBufferSource();source.buffer=buffer;source.connect(offline.destination);source.start(); | |
| const rendered=await offline.startRendering();active(); | |
| return wav(rendered.getChannelData(0),16000); | |
| }finally{this.cleanup(session);if(this.session===session)this.session=null;} | |
| } | |
| cleanup(session){ | |
| clearTimeout(session.timer); | |
| if(session.processor){session.processor.onaudioprocess=null;session.processor.disconnect();} | |
| session.source?.disconnect();session.stream?.getTracks().forEach(t=>t.stop());session.context?.close().catch(()=>{}); | |
| session.processor=session.source=session.stream=session.context=null; | |
| } | |
| cancel(){ | |
| const session=this.session;if(!session)return; | |
| this.session=null;session.cancelled=true; | |
| const reject=session.reject;session.reject=null;this.cleanup(session); | |
| reject?.(new DOMException('Recording stopped','AbortError')); | |
| } | |
| } | |
| export function wav(data,rate){ | |
| const bytes=new ArrayBuffer(44+data.length*2),view=new DataView(bytes);const str=(at,s)=>{for(let i=0;i<s.length;i++)view.setUint8(at+i,s.charCodeAt(i));}; | |
| str(0,'RIFF');view.setUint32(4,36+data.length*2,true);str(8,'WAVE');str(12,'fmt ');view.setUint32(16,16,true);view.setUint16(20,1,true);view.setUint16(22,1,true);view.setUint32(24,rate,true);view.setUint32(28,rate*2,true);view.setUint16(32,2,true);view.setUint16(34,16,true);str(36,'data');view.setUint32(40,data.length*2,true); | |
| for(let i=0;i<data.length;i++)view.setInt16(44+i*2,Math.max(-1,Math.min(1,data[i]))*(data[i]<0?32768:32767),true); | |
| return new Blob([bytes],{type:'audio/wav'}); | |
| } | |