@gjsify/speech-recognition 0.64.62 → 0.64.65
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/README.md +6 -0
- package/lib/esm/backend.js +1 -1
- package/lib/esm/events.js +1 -1
- package/lib/esm/fake-engine.js +1 -1
- package/lib/esm/fake-offline-engine.js +1 -1
- package/lib/esm/index.js +1 -1
- package/lib/esm/offline-engine.js +1 -1
- package/lib/esm/pipeline.js +1 -0
- package/lib/esm/recognition.js +1 -1
- package/lib/esm/transcribe.js +1 -1
- package/lib/types/backend.d.ts +21 -2
- package/lib/types/endpoint.spec.d.ts +2 -0
- package/lib/types/events.d.ts +14 -0
- package/lib/types/fake-engine.d.ts +4 -0
- package/lib/types/index.d.ts +5 -3
- package/lib/types/offline-engine.d.ts +2 -2
- package/lib/types/pipeline.d.ts +62 -0
- package/lib/types/recognition.d.ts +11 -1
- package/package.json +10 -10
package/README.md
CHANGED
|
@@ -73,6 +73,12 @@ Errors use the spec vocabulary plus `language-not-supported` (no model for `lang
|
|
|
73
73
|
|
|
74
74
|
The VAD (300 ms of silence) is the primary finalizer, so a final result lands roughly 300 ms after the speaker stops plus decoding. When the VAD model is not cached, the zipformer's own endpoint detection finalizes instead, which is later and less steady.
|
|
75
75
|
|
|
76
|
+
### Ending a turn: `endpoint`, rules and the pipeline
|
|
77
|
+
|
|
78
|
+
`endpoint` (not in the Web Speech draft) fires once per utterance, just before `speechend` and the final `result`, with `event.source` = `'vad'` or `'model'`. `new SpeechRecognition({ endpoint: { minSilenceMs, rules } })` sets how long the default detector waits and the model's own trailing-silence rules (`EndpointRules`, seconds). The model reads one decode step (about 1.4 s) ahead, so its endpoint arrives that long after the rule's silence: measured 2.9-3.2 s on a phone with the defaults. For a turn that ends at a chosen silence, use the detector.
|
|
79
|
+
|
|
80
|
+
An app that owns its audio loop uses `openStreamingPipeline({ lang, endOfTurnMs })` (or `createStreamingPipeline({ engine, vad })`; `installStreamingPipeline()` fetches the model and the VAD model): `accept(Float32Array)` answers `{ text, endpoint, endpointSource, speechStart }`, a detector endpoint carries the FINAL text (the pipeline pads one decode step itself, so the caller feeds no silence), and `finish()` does the same at the end of audio. `@gjsify/media-capture`'s `PcmSource.readSamples()` yields the `Float32Array` chunks it takes.
|
|
81
|
+
|
|
76
82
|
## Latency budget and engine candidates
|
|
77
83
|
|
|
78
84
|
[Lotsman](https://github.com/JumpLink/lotsman) needs a spoken conversation mode with **500 ms from end of speech to text**. Its measurements on an i9-10900K / RX 6600 (2026-10-28 to 30), as recorded in ADR 0127:
|
package/lib/esm/backend.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./_virtual/_rolldown/runtime.js";import{getLoadError as e,hasNativeSherpa as t,loadNativeSherpa as n}from"@gjsify/sherpa-native";import{hostOs as
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";import{getLoadError as e,hasNativeSherpa as t,loadNativeSherpa as n,openAsync as r}from"@gjsify/sherpa-native";import{hostOs as i}from"@gjsify/utils/core";function hasRecognitionBackend(){let e=i();return e===`darwin`||e===`win32`?!1:t()}function describeRecognitionBackend(){if(!hasRecognitionBackend()){let t=e();return`none: @gjsify/sherpa-native is not available on this host${t?` (${t.message})`:``}`}let t=n();return`sherpa-onnx ${t.version()} on onnxruntime ${t.onnxruntime_version()} (@gjsify/sherpa-native)`}function ruleProperties(e={}){let t={};for(let[n,r]of[[`rule1MinTrailingSilence`,`rule1_min_trailing_silence`],[`rule2MinTrailingSilence`,`rule2_min_trailing_silence`],[`rule3MinUtteranceLength`,`rule3_min_utterance_length`]]){let i=e[n];if(i!==void 0){if(!(i>0))throw RangeError(`EndpointRules.${n} must be a positive number of seconds, got ${i}`);t[r]=i}}return t}function createSherpaEngine(e){let t=n();if(t===null)throw Error(describeRecognitionBackend());let i=new t.OnlineRecognizer({encoder:e.encoder,decoder:e.decoder,joiner:e.joiner,tokens:e.tokens,sample_rate:e.sampleRate,num_threads:e.numThreads??1,enable_endpoint:!0,...ruleProperties(e.endpointRules)}),a=null,feed=t=>{let n=a;for(n.accept(e.sampleRate,t);n.is_ready();)n.decode();return{text:n.get_text(),endpoint:n.is_endpoint()}};return{async open(){await r(i),a??=i.create_stream(null)},accept:feed,flushTail(){return feed(new Float32Array(Math.round(e.sampleRate*1.5)))},detail(){try{let e=JSON.parse(a.get_json());return{tokens:e.tokens??[],timestamps:e.timestamps??[],logProbs:e.ys_probs??[]}}catch{return{tokens:[],timestamps:[],logProbs:[]}}},reset(){a.reset()},close(){a?.close(),a=null,i.close()}}}export{createSherpaEngine,describeRecognitionBackend,hasRecognitionBackend,ruleProperties};
|
package/lib/esm/events.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./_virtual/_rolldown/runtime.js";import{SpeechRecognitionResultList as e}from"./results.js";import{Event as t}from"@gjsify/dom-events";var SpeechRecognitionEvent=class extends t{resultIndex;results;constructor(t,n={}){super(t,n),this.resultIndex=n.resultIndex??0,this.results=n.results??new e}get[Symbol.toStringTag](){return`SpeechRecognitionEvent`}},SpeechRecognitionErrorEvent=class extends t{error;message;constructor(e,t){super(e,t),this.error=t.error,this.message=t.message??``}get[Symbol.toStringTag](){return`SpeechRecognitionErrorEvent`}};function defineEventHandler(e,t){let n=Symbol(`on${t}`);Object.defineProperty(e,`on${t}`,{configurable:!0,enumerable:!0,get(){return this[n]??null},set(e){this[n]&&this.removeEventListener(t,this[n]),this[n]=typeof e==`function`?e:null,this[n]&&this.addEventListener(t,this[n])}})}export{SpeechRecognitionErrorEvent,SpeechRecognitionEvent,defineEventHandler};
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";import{SpeechRecognitionResultList as e}from"./results.js";import{Event as t}from"@gjsify/dom-events";var SpeechRecognitionEvent=class extends t{resultIndex;results;constructor(t,n={}){super(t,n),this.resultIndex=n.resultIndex??0,this.results=n.results??new e}get[Symbol.toStringTag](){return`SpeechRecognitionEvent`}},SpeechRecognitionEndpointEvent=class extends t{source;constructor(e,t){super(e),this.source=t.source}get[Symbol.toStringTag](){return`SpeechRecognitionEndpointEvent`}},SpeechRecognitionErrorEvent=class extends t{error;message;constructor(e,t){super(e,t),this.error=t.error,this.message=t.message??``}get[Symbol.toStringTag](){return`SpeechRecognitionErrorEvent`}};function defineEventHandler(e,t){let n=Symbol(`on${t}`);Object.defineProperty(e,`on${t}`,{configurable:!0,enumerable:!0,get(){return this[n]??null},set(e){this[n]&&this.removeEventListener(t,this[n]),this[n]=typeof e==`function`?e:null,this[n]&&this.addEventListener(t,this[n])}})}export{SpeechRecognitionEndpointEvent,SpeechRecognitionErrorEvent,SpeechRecognitionEvent,defineEventHandler};
|
package/lib/esm/fake-engine.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./_virtual/_rolldown/runtime.js";function createFakeRecognizerEngine(){let e=[],t=0,n={text:``},r=null,i={tokens:[],timestamps:[],logProbs:[]},a={samples:0,resets:0,tails:0,opened:!1,closed:!1},frame=e=>({text:e.text,endpoint:e.endpoint??!1});return{script(n){e=[...n],t=0},setTailText(e){r=e},setDetail(e){i={tokens:[],timestamps:[],logProbs:[],...e}},get samplesAccepted(){return a.samples},get resets(){return a.resets},get tailFlushes(){return a.tails},get opened(){return a.opened},get closed(){return a.closed},open(){a.opened=!0},accept(r){return a.samples+=r.length,t<e.length&&(n=e[t++]),frame(n)},flushTail(){return a.tails++,frame({text:r??n.text})},detail:()=>i,reset(){a.resets++,n={text:``},r=null},close(){a.closed=!0}}}export{createFakeRecognizerEngine};
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";function createFakeRecognizerEngine(){let e=[],t=0,n={text:``},r=null,i={tokens:[],timestamps:[],logProbs:[]},a={samples:0,resets:0,tails:0,opened:!1,closed:!1,openDelayMs:0,openError:null},frame=e=>({text:e.text,endpoint:e.endpoint??!1});return{script(n){e=[...n],t=0},setTailText(e){r=e},setDetail(e){i={tokens:[],timestamps:[],logProbs:[],...e}},get samplesAccepted(){return a.samples},get resets(){return a.resets},get tailFlushes(){return a.tails},get opened(){return a.opened},get closed(){return a.closed},async open(){if(a.openDelayMs>0&&await new Promise(e=>setTimeout(e,a.openDelayMs)),a.openError!==null)throw a.openError;a.opened=!0},setOpenDelay(e){a.openDelayMs=e},failOpen(e){a.openError=e},accept(r){return a.samples+=r.length,t<e.length&&(n=e[t++]),frame(n)},flushTail(){return a.tails++,frame({text:r??n.text})},detail:()=>i,reset(){a.resets++,n={text:``},r=null},close(){a.closed=!0}}}export{createFakeRecognizerEngine};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./_virtual/_rolldown/runtime.js";function createFakeOfflineEngine(e={}){let t={text:``,language:null},n=null,r=[],i=[],a={opened:!1,closed:!1};return{name:e.name??`fake`,hotwords:e.hotwords??!1,answer(e){t={text:e.text??``,language:e.language??null}},failWith(e){n=e},recordings:r,calls:i,get opened(){return a.opened},get closed(){return a.closed},open(){a.opened=!0},transcribe(e,a){if(r.push(e),i.push(a),n!==null)throw n;return{...t}},close(){a.closed=!0}}}export{createFakeOfflineEngine};
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";function createFakeOfflineEngine(e={}){let t={text:``,language:null},n=null,r=[],i=[],a={opened:!1,closed:!1};return{name:e.name??`fake`,hotwords:e.hotwords??!1,answer(e){t={text:e.text??``,language:e.language??null}},failWith(e){n=e},recordings:r,calls:i,get opened(){return a.opened},get closed(){return a.closed},async open(){a.opened=!0},transcribe(e,a){if(r.push(e),i.push(a),n!==null)throw n;return{...t}},close(){a.closed=!0}}}export{createFakeOfflineEngine};
|
package/lib/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createSherpaEngine as e,describeRecognitionBackend as t,hasRecognitionBackend as n}from"./backend.js";import{SpeechRecognitionAlternative as r,SpeechRecognitionPhrase as i,SpeechRecognitionResult as a,SpeechRecognitionResultList as o}from"./results.js";import{
|
|
1
|
+
import{createSherpaEngine as e,describeRecognitionBackend as t,hasRecognitionBackend as n}from"./backend.js";import{SpeechRecognitionAlternative as r,SpeechRecognitionPhrase as i,SpeechRecognitionResult as a,SpeechRecognitionResultList as o}from"./results.js";import{SpeechRecognitionEndpointEvent as s,SpeechRecognitionErrorEvent as c,SpeechRecognitionEvent as l}from"./events.js";import{createFakeRecognizerEngine as u}from"./fake-engine.js";import{createFakeOfflineEngine as d}from"./fake-offline-engine.js";import{DEFAULT_RECOGNITION_MODEL as f,DEFAULT_TRANSCRIBE_MODEL as p,RECOGNITION_MODELS as m,findRecognitionModel as h,modelFor as g}from"./model-manifest.js";import{available as _,install as v,isModelCached as y,modelCacheDir as b,uninstall as x}from"./models.js";import{createStreamingPipeline as S,installStreamingPipeline as C,openStreamingPipeline as w}from"./pipeline.js";import{SpeechRecognition as T}from"./recognition.js";import{createSherpaOfflineEngine as E}from"./offline-engine.js";import{TRANSCRIBE_SAMPLE_RATE as D,transcribe as O}from"./transcribe.js";export{f as DEFAULT_RECOGNITION_MODEL,p as DEFAULT_TRANSCRIBE_MODEL,m as RECOGNITION_MODELS,T as SpeechRecognition,r as SpeechRecognitionAlternative,s as SpeechRecognitionEndpointEvent,c as SpeechRecognitionErrorEvent,l as SpeechRecognitionEvent,i as SpeechRecognitionPhrase,a as SpeechRecognitionResult,o as SpeechRecognitionResultList,D as TRANSCRIBE_SAMPLE_RATE,_ as available,d as createFakeOfflineEngine,u as createFakeRecognizerEngine,e as createSherpaEngine,E as createSherpaOfflineEngine,S as createStreamingPipeline,t as describeRecognitionBackend,h as findRecognitionModel,n as hasRecognitionBackend,v as install,C as installStreamingPipeline,y as isModelCached,b as modelCacheDir,g as modelFor,w as openStreamingPipeline,O as transcribe,x as uninstall};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./_virtual/_rolldown/runtime.js";import{describeRecognitionBackend as e}from"./backend.js";import{loadNativeSherpa as t}from"@gjsify/sherpa-native";function createSherpaOfflineEngine(
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";import{describeRecognitionBackend as e}from"./backend.js";import{loadNativeSherpa as t,openAsync as n}from"@gjsify/sherpa-native";function createSherpaOfflineEngine(r){let i=t();if(i===null)throw Error(e());let a=new i.OfflineRecognizer({encoder:r.encoder,decoder:r.decoder,joiner:r.joiner,tokens:r.tokens,model_type:r.modelType??null,sample_rate:r.sampleRate,num_threads:r.numThreads??2});return{name:r.name,hotwords:!1,open(){return n(a)},transcribe(e){let t=a.create_stream(null);try{t.accept(r.sampleRate,e),t.decode();let n=t.get_text().trim(),i=null;try{let e=JSON.parse(t.get_json()).lang;typeof e==`string`&&e!==``&&(i=e)}catch{}return{text:n,language:i}}finally{t.close()}},close(){a.close()}}}export{createSherpaOfflineEngine};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";import{createSherpaEngine as e,hasRecognitionBackend as t}from"./backend.js";import{modelFor as n}from"./model-manifest.js";import{install as r,isModelCached as i,resolveRecognitionModel as a}from"./models.js";import{available as o,createVad as s,install as c}from"@gjsify/vad";function createStreamingPipeline(e){let{engine:t}=e,n=e.vad??null,r=!1;return{accept(e){let i=n?n.accept(e):[],a=t.accept(e),o=!r&&(i.some(e=>e.type===`speech-start`)||a.text!==``);return(a.text!==``||i.length>0)&&(r=!0),i.some(e=>e.type===`speech-end`)?(r=!1,{text:t.flushTail().text,endpoint:!0,endpointSource:`vad`,speechStart:o}):a.endpoint?(r=!1,{text:a.text,endpoint:!0,endpointSource:`model`,speechStart:o}):{text:a.text,endpoint:!1,speechStart:o}},finish(){return n?.flush(),{text:t.flushTail().text}},detail:()=>t.detail(),reset(){r=!1,t.reset()},close(){n?.close(),t.close()}}}async function openStreamingPipeline(r){if(!(r.endOfTurnMs>0))throw RangeError(`endOfTurnMs must be positive, got ${r.endOfTurnMs}`);let c=n(r.lang??`de`,r.quality??`dictation`);if(c===void 0)throw Error(`No streaming recognition model for '${r.lang??`de`}'`);if(!t()||!i(c))throw Error(`Model '${c.id}' is not usable here — check available() and install() it`);let l=a(c),u=r.endOfTurnMs/1e3,d=e({encoder:l[c.encoder],decoder:l[c.decoder],joiner:l[c.joiner],tokens:l[c.tokens],sampleRate:c.sampleRate,...r.numThreads===void 0?{}:{numThreads:r.numThreads},endpointRules:{rule1MinTrailingSilence:u,rule2MinTrailingSilence:u,...r.rules}});try{await d.open()}catch(e){throw d.close(),e}let f=null;return o()===`available`&&(f=s({minSilenceMs:r.endOfTurnMs,maxSpeechMs:6e4,bufferSeconds:90}),f.open()),createStreamingPipeline({engine:d,vad:f})}async function installStreamingPipeline(e){if(!await r({...e,kind:`streaming`}))return!1;if(o()!==`available`)try{await c(void 0,{signal:e.signal})}catch{}return!0}export{createStreamingPipeline,installStreamingPipeline,openStreamingPipeline};
|
package/lib/esm/recognition.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./_virtual/_rolldown/runtime.js";import{createSherpaEngine as e,hasRecognitionBackend as t}from"./backend.js";import{SpeechRecognitionAlternative as n,SpeechRecognitionResult as r,SpeechRecognitionResultList as i,namedError as a}from"./results.js";import{
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";import{createSherpaEngine as e,hasRecognitionBackend as t}from"./backend.js";import{SpeechRecognitionAlternative as n,SpeechRecognitionResult as r,SpeechRecognitionResultList as i,namedError as a}from"./results.js";import{SpeechRecognitionEndpointEvent as o,SpeechRecognitionErrorEvent as s,SpeechRecognitionEvent as c,defineEventHandler as l}from"./events.js";import{modelFor as u}from"./model-manifest.js";import{available as d,install as f,isModelCached as p,resolveRecognitionModel as m}from"./models.js";import{createStreamingPipeline as h}from"./pipeline.js";import{EventTarget as g}from"@gjsify/dom-events";import{openPcmSource as _}from"@gjsify/media-capture";import{available as v,createVad as y,toFloatSamples as b}from"@gjsify/vad";const x=[`audiostart`,`soundstart`,`speechstart`,`endpoint`,`speechend`,`soundend`,`audioend`,`result`,`nomatch`,`error`,`start`,`end`],S=16e3;function systemLanguage(){try{return new Intl.DateTimeFormat().resolvedOptions().locale}catch{return`en-US`}}function mean(e){return e.length===0?0:e.reduce((e,t)=>e+t,0)/e.length}var SpeechRecognition=class extends g{lang=``;continuous=!1;interimResults=!1;maxAlternatives=1;unspokenPunctuation=!1;phrases=[];#e;#t=!1;#n=!1;#r=!1;#i=null;constructor(e={}){super(),this.#e=e}get processLocally(){return!0}set processLocally(e){if(!e)throw a(`SpeechRecognition.processLocally cannot be false: gjsify has no recognition service to reach`,`NotSupportedError`)}static available(e){return d(e)}static install(e){return f(e)}start(e){if(this.#t)throw a(`SpeechRecognition has already started`,`InvalidStateError`);let t=e;if(t!==void 0&&(t.kind!==`audio`||t.readyState!==`live`))throw a(`start(track) needs a live audio MediaStreamTrack`,`InvalidStateError`);this.#t=!0,this.#n=!1,this.#r=!1;let n={lang:this.lang||systemLanguage(),quality:`command`,continuous:this.continuous,interim:this.interimResults,phrases:this.phrases.length,track:t!==void 0};queueMicrotask(()=>{this.#s(n).catch(e=>{this.#o(`audio-capture`,e instanceof Error?e.message:String(e))})})}stop(){!this.#t||this.#n||(this.#n=!0,this.#i?.stop())}abort(){!this.#t||this.#r||(this.#n=!0,this.#r=!0,this.#i?.stop())}#a(e){this.dispatchEvent(new c(e))}#o(e,t){this.dispatchEvent(new s(`error`,{error:e,message:t})),this.#t&&(this.#t=!1,this.#a(`end`))}async#s(n){let r=u(n.lang,n.quality);if(r===void 0)return this.#o(`language-not-supported`,`No recognition model for '${n.lang}' at quality '${n.quality}'`);if(n.phrases>0&&!r.hotwords)return this.#o(`phrases-not-supported`,`Model '${r.id}' cannot be biased with phrases`);if(n.track)return this.#o(`audio-capture`,`start(track) is not supported yet — call start() for the default microphone`);let i;if(this.#e.engine!==void 0)i=this.#e.engine(r);else{if(!t()||!p(r))return this.#o(`service-not-allowed`,`Model '${r.id}' is not usable here — check SpeechRecognition.available() and install() it`);let n=m(r);i=e({encoder:n[r.encoder],decoder:n[r.decoder],joiner:n[r.joiner],tokens:n[r.tokens],sampleRate:r.sampleRate,...this.#e.endpoint?.rules===void 0?{}:{endpointRules:this.#e.endpoint.rules}})}try{await i.open()}catch(e){return i.close(),this.#o(`service-not-allowed`,`The recognizer could not load: ${e instanceof Error?e.message:e}`)}if(this.#n){i.close(),this.#t=!1,this.#a(`end`);return}let a=this.#c(),o;try{o=this.#e.source?.()??_({sampleRate:S,format:`S16LE`}),o.start?.()}catch(e){return i.close(),a?.close(),this.#o(`audio-capture`,e instanceof Error?e.message:String(e))}this.#i=o,this.#n&&o.stop(),this.#a(`start`);try{await this.#l(n,i,a,o)}catch(e){this.dispatchEvent(new s(`error`,{error:`audio-capture`,message:e instanceof Error?e.message:String(e)}))}finally{this.#i=null,o.stop(),a?.close(),i.close(),this.#t=!1,this.#a(`end`)}}#c(){try{if(this.#e.vad!==void 0){let e=this.#e.vad();return e?.open(),e}if(v()!==`available`)return null;let e=y({minSilenceMs:this.#e.endpoint?.minSilenceMs??300});return e.open(),e}catch{return null}}async#l(e,t,a,l){let u=l.sampleRate??S,d=[],f=!1,p=!1,m=``,g=0,_=0,v=!1,list=e=>new i(e?[...d,e]:d),spaced=(e,t)=>t>0?` ${e}`:e,beginSound=()=>{p||(p=!0,this.#a(`soundstart`),this.#a(`speechstart`))},finalize=(t,i)=>{let a=t.trim(),s=y.detail();y.reset(),i!==void 0&&this.dispatchEvent(new o(`endpoint`,{source:i}));let l=p;p&&(p=!1,this.#a(`speechend`),this.#a(`soundend`)),m=``;let f=_/u;if(_=g,a===``){l&&(this.#a(`nomatch`),e.continuous||(v=!0));return}let h=s.logProbs.map(e=>Math.exp(e)),b=s.timestamps,x=new r({alternatives:[new n(spaced(a,d.length),mean(h))],isFinal:!0,speechStartTime:f+(b.length>0?b[0]:0),speechEndTime:b.length>0?f+b[b.length-1]:g/u});d.push(x),this.dispatchEvent(new c(`result`,{resultIndex:d.length-1,results:list()})),e.continuous||(v=!0)},y=h({engine:t,vad:a});for(;!v;){let t=await l.read();if(t===null||this.#r)break;f||(f=!0,this.#a(`audiostart`));let i=b(t,l.format??`S16LE`);g+=i.length;let a=y.accept(i);if((a.speechStart||a.text!==``)&&beginSound(),a.text!==``&&a.text!==m&&e.interim&&!a.endpoint){m=a.text;let e=new r({alternatives:[new n(spaced(a.text.trim(),d.length),0)],isFinal:!1,speechStartTime:_/u,speechEndTime:g/u});this.dispatchEvent(new c(`result`,{resultIndex:d.length,results:list(e)}))}a.endpoint&&finalize(a.text,a.endpointSource)}if(!this.#r){if(!v&&f){let e=y.finish().text.trim();(p||e!==``)&&finalize(e)}d.length===0&&this.dispatchEvent(new s(`error`,{error:`no-speech`,message:``}))}f&&this.#a(`audioend`)}};for(let e of x)l(SpeechRecognition.prototype,e);export{SpeechRecognition};
|
package/lib/esm/transcribe.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./_virtual/_rolldown/runtime.js";import{hasRecognitionBackend as e}from"./backend.js";import{namedError as t}from"./results.js";import{findRecognitionModel as n}from"./model-manifest.js";import{resolveRecognitionModel as r}from"./models.js";import{createSherpaOfflineEngine as i}from"./offline-engine.js";import{openPcmSource as a}from"@gjsify/media-capture";const o=16e3;function throwIfAborted(e){if(e?.aborted)throw t(`transcribe() was aborted`,`AbortError`)}async function readFile(e,t){let n=a({file:e,sampleRate:o,format:`F32LE`}),r=[],i=0;try{for(;;){throwIfAborted(t);let e=await n.read();if(e===null)break;let a=new Float32Array(e.byteLength>>2);new Uint8Array(a.buffer).set(e.subarray(0,a.length*4)),r.push(a),i+=a.length}}finally{n.stop()}let s=new Float32Array(i),c=0;for(let e of r)s.set(e,c),c+=e.length;return s}async function samplesOf(e,t){if(e instanceof Float32Array)return e;if(typeof e==`string`)return readFile(e,t);if(typeof e==`object`&&e&&typeof e.get_path==`function`){let n=e.get_path();if(n===null)throw TypeError(`transcribe(): the Gio.File has no local path`);return readFile(n,t)}throw TypeError(`transcribe(): source must be a Float32Array, a file path or a Gio.File`)}async function transcribe(a,o={}){let s=n(o.model??`parakeet-tdt-0.6b-v3-int8`);if(s===void 0)throw t(`Unknown recognition model '${o.model}'`,`NotFoundError`);if(s.kind!==`offline`)throw TypeError(`transcribe(): model '${s.id}' is a streaming model; pick an offline one`);throwIfAborted(o.signal);let c;if(o.engine!==void 0)c=o.engine(s);else{if(!e())throw t(`transcribe(): no native recognition engine on this host`,`NotSupportedError`);let n;try{n=r(s)}catch(e){throw t(e instanceof Error?e.message:String(e),`NotFoundError`)}c=i({name:`sherpa-onnx/${s.id}`,encoder:n[s.encoder],decoder:n[s.decoder],joiner:n[s.joiner],tokens:n[s.tokens],modelType:s.modelType,sampleRate:s.sampleRate})}let l=await samplesOf(a,o.signal);throwIfAborted(o.signal);let u=c.hotwords&&o.phrases!==void 0&&o.phrases.length>0?o.phrases.map(e=>e.phrase):void 0;c.open();try{let e=c.transcribe(l,{hotwords:u});return{text:e.text,language:e.language,engine:c.name}}finally{c.close()}}export{o as TRANSCRIBE_SAMPLE_RATE,transcribe};
|
|
1
|
+
import"./_virtual/_rolldown/runtime.js";import{hasRecognitionBackend as e}from"./backend.js";import{namedError as t}from"./results.js";import{findRecognitionModel as n}from"./model-manifest.js";import{resolveRecognitionModel as r}from"./models.js";import{createSherpaOfflineEngine as i}from"./offline-engine.js";import{openPcmSource as a}from"@gjsify/media-capture";const o=16e3;function throwIfAborted(e){if(e?.aborted)throw t(`transcribe() was aborted`,`AbortError`)}async function readFile(e,t){let n=a({file:e,sampleRate:o,format:`F32LE`}),r=[],i=0;try{for(;;){throwIfAborted(t);let e=await n.read();if(e===null)break;let a=new Float32Array(e.byteLength>>2);new Uint8Array(a.buffer).set(e.subarray(0,a.length*4)),r.push(a),i+=a.length}}finally{n.stop()}let s=new Float32Array(i),c=0;for(let e of r)s.set(e,c),c+=e.length;return s}async function samplesOf(e,t){if(e instanceof Float32Array)return e;if(typeof e==`string`)return readFile(e,t);if(typeof e==`object`&&e&&typeof e.get_path==`function`){let n=e.get_path();if(n===null)throw TypeError(`transcribe(): the Gio.File has no local path`);return readFile(n,t)}throw TypeError(`transcribe(): source must be a Float32Array, a file path or a Gio.File`)}async function transcribe(a,o={}){let s=n(o.model??`parakeet-tdt-0.6b-v3-int8`);if(s===void 0)throw t(`Unknown recognition model '${o.model}'`,`NotFoundError`);if(s.kind!==`offline`)throw TypeError(`transcribe(): model '${s.id}' is a streaming model; pick an offline one`);throwIfAborted(o.signal);let c;if(o.engine!==void 0)c=o.engine(s);else{if(!e())throw t(`transcribe(): no native recognition engine on this host`,`NotSupportedError`);let n;try{n=r(s)}catch(e){throw t(e instanceof Error?e.message:String(e),`NotFoundError`)}c=i({name:`sherpa-onnx/${s.id}`,encoder:n[s.encoder],decoder:n[s.decoder],joiner:n[s.joiner],tokens:n[s.tokens],modelType:s.modelType,sampleRate:s.sampleRate})}let l=await samplesOf(a,o.signal);throwIfAborted(o.signal);let u=c.hotwords&&o.phrases!==void 0&&o.phrases.length>0?o.phrases.map(e=>e.phrase):void 0;await c.open();try{let e=c.transcribe(l,{hotwords:u});return{text:e.text,language:e.language,engine:c.name}}finally{c.close()}}export{o as TRANSCRIBE_SAMPLE_RATE,transcribe};
|
package/lib/types/backend.d.ts
CHANGED
|
@@ -19,8 +19,11 @@ export interface RecognizerDetail {
|
|
|
19
19
|
}
|
|
20
20
|
/** The seam the session talks to. */
|
|
21
21
|
export interface RecognizerEngine {
|
|
22
|
-
/**
|
|
23
|
-
|
|
22
|
+
/**
|
|
23
|
+
* Load the model off the main thread; the promise settles on the main loop, which keeps running
|
|
24
|
+
* meanwhile. Rejects when the model cannot be opened, or when {@link close} runs before it is done.
|
|
25
|
+
*/
|
|
26
|
+
open(): Promise<void>;
|
|
24
27
|
/** Feed mono float samples at the engine's rate and decode everything that became ready. */
|
|
25
28
|
accept(samples: Float32Array): RecognizerFrame;
|
|
26
29
|
/** Pad the tail with silence so the last tokens are emitted, and decode. */
|
|
@@ -32,6 +35,19 @@ export interface RecognizerEngine {
|
|
|
32
35
|
/** Release the model. Idempotent. */
|
|
33
36
|
close(): void;
|
|
34
37
|
}
|
|
38
|
+
/**
|
|
39
|
+
* The model's own endpoint rules, in seconds of audio; unset keeps sherpa-onnx's default. The
|
|
40
|
+
* model reads one decode step (about 1.4 s) ahead, so an endpoint arrives that long after the
|
|
41
|
+
* rule's silence has passed: for a turn end at a chosen silence use `createStreamingPipeline`.
|
|
42
|
+
*/
|
|
43
|
+
export interface EndpointRules {
|
|
44
|
+
/** Trailing silence that ends an utterance even before any word was decoded. Default 2.4. */
|
|
45
|
+
rule1MinTrailingSilence?: number;
|
|
46
|
+
/** Trailing silence that ends an utterance after at least one word. Default 1.2. */
|
|
47
|
+
rule2MinTrailingSilence?: number;
|
|
48
|
+
/** Utterance length that is cut regardless of silence. Default 20. */
|
|
49
|
+
rule3MinUtteranceLength?: number;
|
|
50
|
+
}
|
|
35
51
|
export interface SherpaEngineConfig {
|
|
36
52
|
encoder: string;
|
|
37
53
|
decoder: string;
|
|
@@ -39,6 +55,9 @@ export interface SherpaEngineConfig {
|
|
|
39
55
|
tokens: string;
|
|
40
56
|
sampleRate: number;
|
|
41
57
|
numThreads?: number;
|
|
58
|
+
endpointRules?: EndpointRules;
|
|
42
59
|
}
|
|
60
|
+
/** The `OnlineRecognizer` construct properties for `rules`; throws on a rule that is not a positive number. */
|
|
61
|
+
export declare function ruleProperties(rules?: EndpointRules): Record<string, number>;
|
|
43
62
|
/** A {@link RecognizerEngine} over `GjsifySherpa.OnlineRecognizer`. */
|
|
44
63
|
export declare function createSherpaEngine(config: SherpaEngineConfig): RecognizerEngine;
|
package/lib/types/events.d.ts
CHANGED
|
@@ -14,6 +14,20 @@ export declare class SpeechRecognitionEvent extends Event {
|
|
|
14
14
|
constructor(type: string, init?: SpeechRecognitionEventInit);
|
|
15
15
|
get [Symbol.toStringTag](): string;
|
|
16
16
|
}
|
|
17
|
+
/** Who decided the utterance ended: the voice activity detector, or the model's own trailing-silence rule. */
|
|
18
|
+
export type SpeechRecognitionEndpointSource = 'vad' | 'model';
|
|
19
|
+
/**
|
|
20
|
+
* `endpoint` (not in the Web Speech draft): the recognizer decided the utterance ended. It is
|
|
21
|
+
* dispatched just before `speechend` and the final `result`, once per utterance, so an app can
|
|
22
|
+
* act on the decision (end a turn) without waiting for the whole session to finish.
|
|
23
|
+
*/
|
|
24
|
+
export declare class SpeechRecognitionEndpointEvent extends Event {
|
|
25
|
+
readonly source: SpeechRecognitionEndpointSource;
|
|
26
|
+
constructor(type: string, init: {
|
|
27
|
+
source: SpeechRecognitionEndpointSource;
|
|
28
|
+
});
|
|
29
|
+
get [Symbol.toStringTag](): string;
|
|
30
|
+
}
|
|
17
31
|
/** https://webaudio.github.io/web-speech-api/#enumdef-speechrecognitionerrorcode */
|
|
18
32
|
export type SpeechRecognitionErrorCode = 'no-speech' | 'aborted' | 'audio-capture' | 'network' | 'not-allowed' | 'service-not-allowed' | 'language-not-supported' | 'phrases-not-supported';
|
|
19
33
|
export interface SpeechRecognitionErrorEventInit extends SpeechRecognitionEventInit {
|
|
@@ -9,6 +9,10 @@ export interface FakeRecognizerEngine extends RecognizerEngine {
|
|
|
9
9
|
/** What `flushTail()` answers (default: the last text). */
|
|
10
10
|
setTailText(text: string): void;
|
|
11
11
|
setDetail(detail: Partial<RecognizerDetail>): void;
|
|
12
|
+
/** Make `open()` resolve only after this many milliseconds, as a real model load does. */
|
|
13
|
+
setOpenDelay(ms: number): void;
|
|
14
|
+
/** Make `open()` reject with this error. */
|
|
15
|
+
failOpen(error: Error): void;
|
|
12
16
|
readonly samplesAccepted: number;
|
|
13
17
|
readonly resets: number;
|
|
14
18
|
readonly tailFlushes: number;
|
package/lib/types/index.d.ts
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
export { SpeechRecognition } from './recognition.js';
|
|
2
2
|
export type { PcmReader, SpeechRecognitionInit } from './recognition.js';
|
|
3
|
-
export { SpeechRecognitionErrorEvent, SpeechRecognitionEvent } from './events.js';
|
|
4
|
-
export type { SpeechRecognitionErrorCode, SpeechRecognitionErrorEventInit, SpeechRecognitionEventInit, } from './events.js';
|
|
3
|
+
export { SpeechRecognitionEndpointEvent, SpeechRecognitionErrorEvent, SpeechRecognitionEvent } from './events.js';
|
|
4
|
+
export type { SpeechRecognitionEndpointSource, SpeechRecognitionErrorCode, SpeechRecognitionErrorEventInit, SpeechRecognitionEventInit, } from './events.js';
|
|
5
5
|
export { SpeechRecognitionAlternative, SpeechRecognitionPhrase, SpeechRecognitionResult, SpeechRecognitionResultList, } from './results.js';
|
|
6
6
|
export { available, install, isModelCached, modelCacheDir, uninstall } from './models.js';
|
|
7
7
|
export type { SpeechRecognitionAvailability, SpeechRecognitionInstallOptions, SpeechRecognitionOptions, } from './models.js';
|
|
8
8
|
export { DEFAULT_RECOGNITION_MODEL, findRecognitionModel, modelFor, RECOGNITION_MODELS } from './model-manifest.js';
|
|
9
9
|
export type { RecognitionModelEntry, RecognitionQuality } from './model-manifest.js';
|
|
10
10
|
export { createSherpaEngine, describeRecognitionBackend, hasRecognitionBackend } from './backend.js';
|
|
11
|
-
export type { RecognizerDetail, RecognizerEngine, RecognizerFrame, SherpaEngineConfig } from './backend.js';
|
|
11
|
+
export type { EndpointRules, RecognizerDetail, RecognizerEngine, RecognizerFrame, SherpaEngineConfig, } from './backend.js';
|
|
12
|
+
export { createStreamingPipeline, installStreamingPipeline, openStreamingPipeline } from './pipeline.js';
|
|
13
|
+
export type { EndpointSource, PipelineFrame, StreamingPipeline, StreamingPipelineOptions } from './pipeline.js';
|
|
12
14
|
export { createFakeRecognizerEngine } from './fake-engine.js';
|
|
13
15
|
export type { FakeEngineStep, FakeRecognizerEngine } from './fake-engine.js';
|
|
14
16
|
export { DEFAULT_TRANSCRIBE_MODEL } from './model-manifest.js';
|
|
@@ -13,8 +13,8 @@ export interface OfflineEngine {
|
|
|
13
13
|
readonly name: string;
|
|
14
14
|
/** Whether {@link OfflineDecodeOptions.hotwords} changes the result. */
|
|
15
15
|
readonly hotwords: boolean;
|
|
16
|
-
/** Load the model.
|
|
17
|
-
open(): void
|
|
16
|
+
/** Load the model off the main thread; the main loop keeps running. Rejects when it cannot be opened. */
|
|
17
|
+
open(): Promise<void>;
|
|
18
18
|
/** Decode a whole recording: mono Float32 at 16 kHz. */
|
|
19
19
|
transcribe(samples: Float32Array, options?: OfflineDecodeOptions): OfflineResult;
|
|
20
20
|
/** Release the model. Idempotent. */
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type VoiceActivityDetector } from '@gjsify/vad';
|
|
2
|
+
import { type EndpointRules, type RecognizerDetail, type RecognizerEngine } from './backend.js';
|
|
3
|
+
import { type RecognitionQuality } from './model-manifest.js';
|
|
4
|
+
import { type SpeechRecognitionInstallOptions } from './models.js';
|
|
5
|
+
/** Who decided the utterance ended. */
|
|
6
|
+
export type EndpointSource = 'vad' | 'model';
|
|
7
|
+
/** What one chunk of audio did to the pipeline. */
|
|
8
|
+
export interface PipelineFrame {
|
|
9
|
+
/** The hypothesis for the current utterance. After a `vad` endpoint it is FINAL: the tail is flushed. */
|
|
10
|
+
text: string;
|
|
11
|
+
/** The utterance ended with this chunk. */
|
|
12
|
+
endpoint: boolean;
|
|
13
|
+
/** Present exactly when {@link endpoint} is. */
|
|
14
|
+
endpointSource?: EndpointSource;
|
|
15
|
+
/** The detector confirmed speech with this chunk, or the model produced its first text. */
|
|
16
|
+
speechStart: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface StreamingPipeline {
|
|
19
|
+
/** Feed mono float samples at the engine's rate. */
|
|
20
|
+
accept(samples: Float32Array): PipelineFrame;
|
|
21
|
+
/** Audio ended: close what the detector still holds and read the last words. */
|
|
22
|
+
finish(): {
|
|
23
|
+
text: string;
|
|
24
|
+
};
|
|
25
|
+
/** Token detail of the current utterance. Call before {@link reset}. */
|
|
26
|
+
detail(): RecognizerDetail;
|
|
27
|
+
/** Start the next utterance on the same model. */
|
|
28
|
+
reset(): void;
|
|
29
|
+
/** Release the model and the detector. Idempotent. */
|
|
30
|
+
close(): void;
|
|
31
|
+
}
|
|
32
|
+
/** A pipeline over parts you already have. `vad: null` leaves the model's endpoint as the only one. */
|
|
33
|
+
export declare function createStreamingPipeline(parts: {
|
|
34
|
+
engine: RecognizerEngine;
|
|
35
|
+
vad?: VoiceActivityDetector | null;
|
|
36
|
+
}): StreamingPipeline;
|
|
37
|
+
export interface StreamingPipelineOptions {
|
|
38
|
+
/** BCP 47 tag. Default `de`. */
|
|
39
|
+
lang?: string;
|
|
40
|
+
/** Default `dictation`. */
|
|
41
|
+
quality?: RecognitionQuality;
|
|
42
|
+
/**
|
|
43
|
+
* Silence after the last word that ends a turn, in ms. The detector waits exactly this long;
|
|
44
|
+
* the model's own rules (the fallback) are set to the same, so neither ends a turn sooner.
|
|
45
|
+
*/
|
|
46
|
+
endOfTurnMs: number;
|
|
47
|
+
/** onnxruntime threads for the recognizer. Default 1. */
|
|
48
|
+
numThreads?: number;
|
|
49
|
+
/** Override the model's trailing-silence rules; they default to `endOfTurnMs`. */
|
|
50
|
+
rules?: EndpointRules;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* The cached model for `lang`, loaded off the main thread, with the VAD when its model is cached.
|
|
54
|
+
* Rejects when the backend or the model is missing — `available()` / `install()` come first.
|
|
55
|
+
*/
|
|
56
|
+
export declare function openStreamingPipeline(options: StreamingPipelineOptions): Promise<StreamingPipeline>;
|
|
57
|
+
/**
|
|
58
|
+
* Fetch what {@link openStreamingPipeline} uses: the streaming model, then the Silero VAD model.
|
|
59
|
+
* `true` once the recognizer is cached. A failed VAD download is not an error: the pipeline then
|
|
60
|
+
* ends turns on the model's own rules, which are later.
|
|
61
|
+
*/
|
|
62
|
+
export declare function installStreamingPipeline(options: Omit<SpeechRecognitionInstallOptions, 'kind'>): Promise<boolean>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type Event, EventTarget } from '@gjsify/dom-events';
|
|
2
2
|
import { type PcmFormat, type VoiceActivityDetector } from '@gjsify/vad';
|
|
3
|
-
import { type RecognizerEngine } from './backend.js';
|
|
3
|
+
import { type EndpointRules, type RecognizerEngine } from './backend.js';
|
|
4
4
|
import { type RecognitionModelEntry } from './model-manifest.js';
|
|
5
5
|
import { type SpeechRecognitionAvailability, type SpeechRecognitionInstallOptions, type SpeechRecognitionOptions } from './models.js';
|
|
6
6
|
import { type SpeechRecognitionPhrase } from './results.js';
|
|
@@ -20,6 +20,15 @@ export interface SpeechRecognitionInit {
|
|
|
20
20
|
vad?: () => VoiceActivityDetector | null;
|
|
21
21
|
/** The audio. Default: the default microphone at 16 kHz mono through `@gjsify/media-capture`. */
|
|
22
22
|
source?: () => PcmReader;
|
|
23
|
+
/**
|
|
24
|
+
* When an utterance ends. `minSilenceMs` is how long the default detector waits (default 300);
|
|
25
|
+
* `rules` are the model's own trailing-silence rules, the fallback for a host without a VAD
|
|
26
|
+
* model. Both apply to the DEFAULT engine and detector only.
|
|
27
|
+
*/
|
|
28
|
+
endpoint?: {
|
|
29
|
+
minSilenceMs?: number;
|
|
30
|
+
rules?: EndpointRules;
|
|
31
|
+
};
|
|
23
32
|
}
|
|
24
33
|
export declare class SpeechRecognition extends EventTarget {
|
|
25
34
|
#private;
|
|
@@ -46,6 +55,7 @@ export interface SpeechRecognition {
|
|
|
46
55
|
onaudiostart: Handler;
|
|
47
56
|
onsoundstart: Handler;
|
|
48
57
|
onspeechstart: Handler;
|
|
58
|
+
onendpoint: Handler;
|
|
49
59
|
onspeechend: Handler;
|
|
50
60
|
onsoundend: Handler;
|
|
51
61
|
onaudioend: Handler;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gjsify/speech-recognition",
|
|
3
|
-
"version": "0.64.
|
|
3
|
+
"version": "0.64.65",
|
|
4
4
|
"description": "Web Speech recognition API (SpeechRecognition and its event and result classes) for GJS, running fully on the device: a streaming zipformer on sherpa-onnx, fed by @gjsify/media-capture and endpointed by @gjsify/vad, plus transcribe() for finished recordings on an offline Parakeet model. Models are fetched on first use, never bundled.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"module": "lib/esm/index.js",
|
|
@@ -45,19 +45,19 @@
|
|
|
45
45
|
"zipformer"
|
|
46
46
|
],
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@gjsify/dom-events": "0.64.
|
|
49
|
-
"@gjsify/media-capture": "0.64.
|
|
50
|
-
"@gjsify/model-store": "0.64.
|
|
51
|
-
"@gjsify/node-globals": "0.64.
|
|
52
|
-
"@gjsify/sherpa-native": "0.64.
|
|
53
|
-
"@gjsify/utils": "0.64.
|
|
54
|
-
"@gjsify/vad": "0.64.
|
|
48
|
+
"@gjsify/dom-events": "0.64.65",
|
|
49
|
+
"@gjsify/media-capture": "0.64.65",
|
|
50
|
+
"@gjsify/model-store": "0.64.65",
|
|
51
|
+
"@gjsify/node-globals": "0.64.65",
|
|
52
|
+
"@gjsify/sherpa-native": "0.64.65",
|
|
53
|
+
"@gjsify/utils": "0.64.65",
|
|
54
|
+
"@gjsify/vad": "0.64.65"
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|
|
57
57
|
"@girs/gjs": "5.4.0",
|
|
58
58
|
"@girs/glib-2.0": "5.4.0",
|
|
59
|
-
"@gjsify/cli": "0.64.
|
|
60
|
-
"@gjsify/unit": "0.64.
|
|
59
|
+
"@gjsify/cli": "0.64.65",
|
|
60
|
+
"@gjsify/unit": "0.64.65",
|
|
61
61
|
"@types/node": "^25.9.2",
|
|
62
62
|
"typescript": "^6.0.3"
|
|
63
63
|
},
|