@oryksa/react-native 1.0.0 → 1.1.1

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/src/index.d.ts CHANGED
@@ -1,53 +1,151 @@
1
- import * as React from "react";
2
- import { StyleProp, ViewStyle } from "react-native";
3
-
4
- export declare const VERSION: string;
5
-
6
- export declare class OryksaError extends Error {
7
- status: number;
8
- code: string;
9
- [key: string]: unknown;
10
- }
11
-
12
- export interface OryksaAgent {
13
- name: string;
14
- avatar: string;
15
- business?: string | null;
16
- gender?: "female" | "male";
17
- greeting?: Record<string, string>;
18
- subtitle?: Record<string, string>;
19
- suggestions?: Record<string, string[]>;
20
- voice_replies?: boolean;
21
- conversation_id?: string;
22
- }
23
-
24
- export interface OryksaReply {
25
- object: "chat_reply";
26
- conversation_id: string;
27
- status: "replied" | "pending";
28
- reply: string | null;
29
- }
30
-
31
- export declare class OryksaClient {
32
- constructor(opts: { token?: string; getToken?: () => Promise<string>; baseUrl?: string; fetch?: typeof fetch; timeoutMs?: number });
33
- agent(): Promise<OryksaAgent>;
34
- send(message: string): Promise<OryksaReply>;
35
- sendAndWait(message: string, maxWaitMs?: number): Promise<string | null>;
36
- messages(): Promise<{ messages: { role: "user" | "assistant"; content: string }[] }>;
37
- }
38
-
39
- export type OryksaLang = "en" | "pt" | "br" | "es";
40
-
41
- export interface OryksaTheme {
42
- accent?: string;
43
- ink?: string;
44
- soft?: string;
45
- background?: string;
46
- muted?: string;
47
- }
48
-
49
- export declare const DEFAULT_THEME: Required<OryksaTheme>;
50
-
51
- export declare function OryksaChat(props: { client: OryksaClient; lang?: OryksaLang; theme?: OryksaTheme; onClose?: () => void }): React.ReactElement;
52
- export declare function OryksaChatModal(props: { client: OryksaClient; lang?: OryksaLang; theme?: OryksaTheme; visible: boolean; onClose: () => void }): React.ReactElement;
53
- export declare function OryksaChatButton(props: { client: OryksaClient; lang?: OryksaLang; theme?: OryksaTheme; position?: "left" | "right"; style?: StyleProp<ViewStyle> }): React.ReactElement;
1
+ import * as React from "react";
2
+ import { StyleProp, ViewStyle } from "react-native";
3
+
4
+ export declare const VERSION: string;
5
+
6
+ export declare class OryksaError extends Error {
7
+ status: number;
8
+ code: string;
9
+ [key: string]: unknown;
10
+ }
11
+
12
+ export interface OryksaAgent {
13
+ name: string;
14
+ avatar: string;
15
+ business?: string | null;
16
+ gender?: "female" | "male";
17
+ greeting?: Record<string, string>;
18
+ subtitle?: Record<string, string>;
19
+ suggestions?: Record<string, string[]>;
20
+ voice_replies?: boolean;
21
+ conversation_id?: string;
22
+ /** The AI photo from "Your AI" in ORYKSA (never the owner's photo). Same as avatar. */
23
+ photo?: string;
24
+ /** ElevenLabs voice chosen for the AI in ORYKSA. */
25
+ voice?: string | null;
26
+ /** Main language of the AI, from ORYKSA. */
27
+ language?: string | null;
28
+ }
29
+
30
+ /** Where the customer is inside your app (sent with each message so the AI answers about it). */
31
+ export interface OryksaAppContext {
32
+ screen?: string;
33
+ title?: string;
34
+ /** What is listed on the screen. Up to 20. */
35
+ items?: string[];
36
+ }
37
+
38
+ export interface OryksaSendOptions {
39
+ appContext?: OryksaAppContext;
40
+ /** The reply will be heard: it also carries a short `speech`. */
41
+ voice?: boolean;
42
+ /** The customer whispered: shorter, whispered answer. */
43
+ whisper?: boolean;
44
+ voiceStats?: Record<string, unknown>;
45
+ maxWaitMs?: number;
46
+ }
47
+
48
+ export interface OryksaReply {
49
+ object: "chat_reply";
50
+ conversation_id: string;
51
+ status: "replied" | "pending";
52
+ reply: string | null;
53
+ /** With voice: the short spoken version of reply (1-2 sentences, no markdown). */
54
+ speech?: string;
55
+ whisper?: boolean;
56
+ }
57
+
58
+ export declare class OryksaClient {
59
+ constructor(opts: { token?: string; getToken?: () => Promise<string>; baseUrl?: string; fetch?: typeof fetch; timeoutMs?: number });
60
+ agent(): Promise<OryksaAgent>;
61
+ send(message: string, opts?: OryksaSendOptions): Promise<OryksaReply>;
62
+ sendAndWait(message: string, opts?: OryksaSendOptions | number): Promise<string | null>;
63
+ sendAndWaitReply(message: string, opts?: OryksaSendOptions): Promise<OryksaReply>;
64
+ messages(): Promise<{ messages: { role: "user" | "assistant"; content: string }[] }>;
65
+ /** The AI's voice (MP3 bytes) for one reply of this conversation; null when not available (show the text only). */
66
+ tts(text: string, opts?: { whisper?: boolean }): Promise<Uint8Array | null>;
67
+ /** 16 kHz mono PCM16 WAV to text. "" = nothing said, null = failed. */
68
+ transcribe(wav: Uint8Array): Promise<string | null>;
69
+ voiceStats(stats: Record<string, unknown>): Promise<void>;
70
+ }
71
+
72
+ /** Audio adapter used by the voice conversation (bring your own for Expo or another audio stack). */
73
+ export interface OryksaAudio {
74
+ /** onChunk receives PCM16 little-endian mono 16 kHz. Resolves false when the mic is not available. */
75
+ startMic(onChunk: (pcm: Uint8Array) => void): Promise<boolean>;
76
+ stopMic(): Promise<void>;
77
+ /** Plays MP3 bytes; resolves when it finished or was stopped. */
78
+ play(mp3: Uint8Array): Promise<void>;
79
+ stopPlayback(): Promise<void>;
80
+ }
81
+
82
+ /** The default adapter: react-native-live-audio-stream + react-native-sound + react-native-fs (null if not installed). */
83
+ export declare function createDefaultAudio(): OryksaAudio | null;
84
+
85
+ export type OryksaVoicePhase = "starting" | "listening" | "hearing" | "thinking" | "speaking" | "muted" | "micError" | "noisy" | "notUnderstood";
86
+
87
+ /** The ORYKSA voice conversation: the same behaviour as the ORYKSA app (only a human voice cuts her off). */
88
+ export declare class OryksaVoiceController {
89
+ constructor(opts: {
90
+ client: OryksaClient;
91
+ audio?: OryksaAudio | null;
92
+ appContext?: () => OryksaAppContext | undefined;
93
+ onUserText?: (text: string) => void;
94
+ onReply?: (text: string) => void;
95
+ onPhase?: (phase: OryksaVoicePhase, controller: OryksaVoiceController) => void;
96
+ });
97
+ phase: OryksaVoicePhase;
98
+ lastReply: string;
99
+ lastHeard: string;
100
+ start(): Promise<void>;
101
+ sendNow(): void;
102
+ say(text: string): Promise<void>;
103
+ toggleMute(): Promise<void>;
104
+ close(): Promise<void>;
105
+ }
106
+
107
+ /** The ORYKSA voice engine (line by line port of the ORYKSA app engine). */
108
+ export declare class Vad {
109
+ constructor(sampleRate?: number);
110
+ static bargeFloor: number;
111
+ static tetoOuvir: number;
112
+ static bargeVozMin: number;
113
+ static quietToCloseMs: number;
114
+ static maxSpeechMs: number;
115
+ static periodicidade(chunk: Uint8Array): number;
116
+ static rmsOf(chunk: Uint8Array): number;
117
+ readonly foiSussurro: boolean;
118
+ capturing: boolean;
119
+ reset(): void;
120
+ newTurn(): void;
121
+ feed(chunk: Uint8Array, speaking?: boolean): { isCapturing: boolean; isDone: boolean; isBargeIn: boolean; spokeMs: number; enough: boolean; isNoise: boolean; level: number };
122
+ }
123
+
124
+ export type OryksaLang = "en" | "pt" | "br" | "es";
125
+
126
+ export interface OryksaTheme {
127
+ accent?: string;
128
+ ink?: string;
129
+ soft?: string;
130
+ background?: string;
131
+ muted?: string;
132
+ }
133
+
134
+ export declare const DEFAULT_THEME: Required<OryksaTheme>;
135
+
136
+ interface OryksaChatVoiceProps {
137
+ /** Where the customer is in your app right now (sent with each message). */
138
+ appContext?: () => OryksaAppContext | undefined;
139
+ /** Shows the microphone when the plan has voice (default true). */
140
+ voice?: boolean;
141
+ /** Audio adapter (default: createDefaultAudio()). */
142
+ audio?: OryksaAudio | null;
143
+ }
144
+
145
+ export declare function OryksaChat(props: { client: OryksaClient; lang?: OryksaLang; theme?: OryksaTheme; onClose?: () => void } & OryksaChatVoiceProps): React.ReactElement;
146
+ export declare function OryksaChatModal(props: { client: OryksaClient; lang?: OryksaLang; theme?: OryksaTheme; visible: boolean; onClose: () => void } & OryksaChatVoiceProps): React.ReactElement;
147
+ export declare function OryksaChatButton(props: { client: OryksaClient; lang?: OryksaLang; theme?: OryksaTheme; position?: "left" | "right"; style?: StyleProp<ViewStyle> } & OryksaChatVoiceProps): React.ReactElement;
148
+ export declare function OryksaVoiceScreen(props: {
149
+ client: OryksaClient; agent: OryksaAgent; visible: boolean; onClose: () => void; lang?: OryksaLang; theme?: OryksaTheme;
150
+ appContext?: () => OryksaAppContext | undefined; onUserText?: (text: string) => void; onReply?: (text: string) => void; audio?: OryksaAudio | null;
151
+ }): React.ReactElement;
package/src/index.js CHANGED
@@ -1,18 +1,28 @@
1
- /*!
2
- * @oryksa/react-native - Official React Native SDK for ORYKSA AI Employees.
3
- * Docs: https://developer.oryksa.com License: MIT
4
- */
5
- "use strict";
6
-
7
- const client = require("./client");
8
- const chat = require("./chat");
9
-
10
- module.exports = {
11
- OryksaClient: client.OryksaClient,
12
- OryksaError: client.OryksaError,
13
- VERSION: client.VERSION,
14
- OryksaChat: chat.OryksaChat,
15
- OryksaChatModal: chat.OryksaChatModal,
16
- OryksaChatButton: chat.OryksaChatButton,
17
- DEFAULT_THEME: chat.DEFAULT_THEME,
18
- };
1
+ /*!
2
+ * @oryksa/react-native - Official React Native SDK for ORYKSA AI Employees.
3
+ * Docs: https://developer.oryksa.com License: MIT
4
+ */
5
+ "use strict";
6
+
7
+ const client = require("./client");
8
+ const chat = require("./chat");
9
+ const voice = require("./voice");
10
+ const voiceScreen = require("./voice-screen");
11
+ const vad = require("./vad");
12
+ const profanity = require("./profanity");
13
+
14
+ module.exports = {
15
+ OryksaClient: client.OryksaClient,
16
+ OryksaError: client.OryksaError,
17
+ VERSION: client.VERSION,
18
+ OryksaChat: chat.OryksaChat,
19
+ OryksaChatModal: chat.OryksaChatModal,
20
+ OryksaChatButton: chat.OryksaChatButton,
21
+ DEFAULT_THEME: chat.DEFAULT_THEME,
22
+ OryksaVoiceController: voice.OryksaVoiceController,
23
+ OryksaVoiceScreen: voiceScreen.OryksaVoiceScreen,
24
+ createDefaultAudio: voice.createDefaultAudio,
25
+ Vad: vad.Vad,
26
+ maskProfanity: profanity.mask,
27
+ loadProfanity: profanity.load,
28
+ };
@@ -0,0 +1,60 @@
1
+ /*!
2
+ * @oryksa/react-native - swear words the customer types show as asterisks (owner rule: every ORYKSA
3
+ * chat). One list for all ORYKSA clients: GET https://app.oryksa.com/widget/profanity.json?lang=
4
+ * (kept 24 hours). The AI's replies already come filtered from the server. License: MIT
5
+ */
6
+ "use strict";
7
+
8
+ const URL_BASE = "https://app.oryksa.com/widget/profanity.json";
9
+ const DAY = 24 * 3600 * 1000;
10
+ const RE = {};
11
+ const AT = {};
12
+
13
+ /** Language key of the list: pt, br, en or es. */
14
+ function key(lang) {
15
+ const l = String(lang || "en");
16
+ return l.indexOf("br") >= 0 ? "br" : l.slice(0, 2);
17
+ }
18
+
19
+ /**
20
+ * Builds the regex. Some JavaScript engines do not know \p{L} / \p{N}: then the same pattern runs with
21
+ * explicit letter ranges (Latin, accents, Greek, Cyrillic) and without the u flag.
22
+ */
23
+ function compile(pattern, flags) {
24
+ try {
25
+ return new RegExp(pattern, flags || "giu");
26
+ } catch (_) {
27
+ const p = pattern.replace(/\\p\{L\}/g, "A-Za-z\\u00C0-\\u024F\\u0370-\\u03FF\\u0400-\\u04FF").replace(/\\p\{N\}/g, "0-9");
28
+ try { return new RegExp(p, String(flags || "gi").replace("u", "")); } catch (_e) { return null; }
29
+ }
30
+ }
31
+
32
+ /** Uses a pattern directly (tests, or your own copy of the list). */
33
+ function use(lang, pattern, flags) {
34
+ const k = key(lang);
35
+ RE[k] = compile(pattern, flags);
36
+ AT[k] = Date.now();
37
+ }
38
+
39
+ /** Loads (or refreshes after 24 h) the list for lang. Never throws. */
40
+ async function load(lang, fetchImpl) {
41
+ const k = key(lang);
42
+ if (AT[k] && Date.now() - AT[k] < DAY) return;
43
+ try {
44
+ const f = fetchImpl || globalThis.fetch;
45
+ const r = await f(URL_BASE + "?lang=" + encodeURIComponent(k));
46
+ if (!r.ok) return;
47
+ const d = await r.json();
48
+ if (d && d.pattern) use(k, d.pattern, d.flags);
49
+ } catch (_) { /* the chat works without it */ }
50
+ }
51
+
52
+ /** text with the swear words replaced by asterisks (at least 3). Unchanged when the list is not loaded. */
53
+ function mask(text, lang) {
54
+ const re = RE[key(lang)];
55
+ if (!re || !text) return text;
56
+ re.lastIndex = 0;
57
+ return String(text).replace(re, (m, pre) => (pre || "") + "*".repeat(Math.max(3, m.slice((pre || "").length).replace(/\s/g, "").length)));
58
+ }
59
+
60
+ module.exports = { load, use, mask, key };
package/src/vad.js ADDED
@@ -0,0 +1,264 @@
1
+ /*!
2
+ * @oryksa/react-native - the ORYKSA voice engine.
3
+ * Decides WHEN someone started and stopped speaking, and whether a sound while she speaks is a human
4
+ * voice that cuts her off. Line by line port of lib/vad.dart of the ORYKSA app (the one engine of the
5
+ * whole ecosystem): every number is the same and has the same reason. Do not change one without running
6
+ * test/vad.test.js with new real recordings.
7
+ * Input: PCM16 little-endian mono chunks (Uint8Array) at 16 kHz. License: MIT
8
+ */
9
+ "use strict";
10
+
11
+ function sample(b, index) {
12
+ const v = b[index * 2] | (b[index * 2 + 1] << 8);
13
+ return v >= 0x8000 ? v - 0x10000 : v;
14
+ }
15
+
16
+ class VadStep {
17
+ constructor(o) {
18
+ this.isCapturing = !!o.isCapturing;
19
+ this.isDone = !!o.isDone;
20
+ this.isBargeIn = !!o.isBargeIn;
21
+ this.spokeMs = o.spokeMs || 0;
22
+ /** Spoke enough to be worth sending? */
23
+ this.enough = !!o.enough;
24
+ /** Not a voice: endless background noise. The reference silence went up. */
25
+ this.isNoise = !!o.isNoise;
26
+ /** Average level of what was recorded. */
27
+ this.level = o.level || 0;
28
+ }
29
+ static done(spokeMs, enough, isNoise, level) {
30
+ return new VadStep({ isDone: true, spokeMs, enough, isNoise: !!isNoise, level: level || 0 });
31
+ }
32
+ }
33
+ VadStep.IDLE = new VadStep({});
34
+ VadStep.CAPTURING = new VadStep({ isCapturing: true });
35
+ VadStep.BARGE_IN = new VadStep({ isBargeIn: true });
36
+
37
+ class Vad {
38
+ constructor(sampleRate) {
39
+ this.sampleRate = sampleRate || 16000;
40
+ this._corrida = 0;
41
+ this._maiorCorrida = 0;
42
+ this._vozHaMs = 99999;
43
+ /** Levels heard in the interruption attempt (for diagnosis). */
44
+ this.perfil = [];
45
+ /** Peak and pitch of the sentence just recorded (whisper detection and quality report). */
46
+ this.picoDaFrase = 0;
47
+ this.tomDaFrase = 0;
48
+ /** Loudest sound while she spoke, and the highest pitch in the interruption attempt. */
49
+ this.maxEnquantoFala = 0;
50
+ this.tomDaInterrupcao = 0;
51
+ this.base = 0;
52
+ this.frames = 0;
53
+ this.speechMs = 0;
54
+ this.quietMs = 0;
55
+ this.capturing = false;
56
+ this._sum = 0;
57
+ this._min = 1;
58
+ this._max = 0;
59
+ this._n = 0;
60
+ }
61
+
62
+ /** A whisper: voice without vocal folds, low and almost without pitch. Contract: peak < 0.09 and pitch < 0.45. */
63
+ get foiSussurro() { return this.picoDaFrase > 0 && this.picoDaFrase < 0.09 && this.tomDaFrase < 0.45; }
64
+
65
+ /**
66
+ * Is this a human VOICE or a noise? Voice is periodic (vocal folds at 70 to 350 Hz); a key, a clap,
67
+ * a door are clicks with no repetition. Normalised autocorrelation at 8 kHz (every other sample),
68
+ * lags 23 (350 Hz) to 114 (70 Hz).
69
+ */
70
+ static periodicidade(chunk) {
71
+ const n = chunk.length >> 1;
72
+ if (n < 512) return 0;
73
+ const m = n >> 1;
74
+ const x = new Float64Array(m);
75
+ let media = 0;
76
+ for (let i = 0; i < m; i++) {
77
+ x[i] = sample(chunk, i * 2) / 32768;
78
+ media += x[i];
79
+ }
80
+ media /= m;
81
+ let energia = 0;
82
+ for (let i = 0; i < m; i++) {
83
+ x[i] -= media;
84
+ energia += x[i] * x[i];
85
+ }
86
+ if (energia <= 0) return 0;
87
+ const lagMin = 23;
88
+ const lagMax = 114;
89
+ let melhor = 0;
90
+ for (let lag = lagMin; lag <= lagMax && lag < m; lag++) {
91
+ let soma = 0;
92
+ for (let i = 0; i + lag < m; i++) soma += x[i] * x[i + lag];
93
+ const r = soma / energia;
94
+ if (r > melhor) melhor = r;
95
+ }
96
+ return melhor;
97
+ }
98
+
99
+ /** Level of this chunk (0 to 1). */
100
+ static rmsOf(chunk) {
101
+ const n = chunk.length >> 1;
102
+ if (n === 0) return 0;
103
+ let sum = 0;
104
+ for (let k = 0; k < n; k++) {
105
+ const v = sample(chunk, k) / 32768;
106
+ sum += v * v;
107
+ }
108
+ return Math.sqrt(sum / n);
109
+ }
110
+
111
+ _noise() {
112
+ const nivel = this._n > 0 ? this._sum / this._n : this.base;
113
+ this.base = Math.min(Math.max(this.base, nivel), Vad.maxNoiseBase);
114
+ return VadStep.done(this.speechMs, false, true, nivel);
115
+ }
116
+
117
+ /** Start from zero, forgetting the learnt silence. Only when a voice session starts. */
118
+ reset() {
119
+ this.base = 0;
120
+ this.frames = 0;
121
+ this.newTurn();
122
+ }
123
+
124
+ /** Ready for the next sentence, KEEPING the learnt silence (the room does not change between sentences). */
125
+ newTurn() {
126
+ this._corrida = 0;
127
+ this._maiorCorrida = 0;
128
+ this._vozHaMs = 99999;
129
+ this.picoDaFrase = 0;
130
+ this.tomDaFrase = 0;
131
+ this.tomDaInterrupcao = 0;
132
+ this.maxEnquantoFala = 0;
133
+ this.perfil.length = 0;
134
+ this.speechMs = 0;
135
+ this.quietMs = 0;
136
+ this.capturing = false;
137
+ this._sum = 0;
138
+ this._min = 1;
139
+ this._max = 0;
140
+ this._n = 0;
141
+ }
142
+
143
+ /** Feeds one chunk (Uint8Array, PCM16 LE). Returns what to do next. */
144
+ feed(chunk, speaking) {
145
+ speaking = !!speaking;
146
+ const n = chunk.length >> 1;
147
+ if (n === 0) return VadStep.IDLE;
148
+ const rms = Vad.rmsOf(chunk);
149
+ const ms = Math.floor((n * 1000) / this.sampleRate);
150
+ this.frames++;
151
+
152
+ // First chunks: learn this place's silence, never above maxBase.
153
+ if (this.frames <= 3 && !speaking) {
154
+ this.base = this.base === 0 ? Math.min(rms, Vad.maxBase) : Math.min(this.base, rms);
155
+ }
156
+ // THE TWO THRESHOLDS, different on purpose. CUTTING: the measured floor, not the room noise.
157
+ // LISTENING: follows the noise, WITH a ceiling (0.10), or she is deaf in a cafe.
158
+ const speakThr = speaking
159
+ ? Math.max(this.base * 2.0, Vad.bargeFloor)
160
+ : Math.min(Math.max(this.base * 3.2, 0.014), Vad.tetoOuvir);
161
+ const quietThr = Math.max(this.base * 1.8, 0.008);
162
+
163
+ // Room noise: goes down fast, up slowly, never learns from a voice-level sound.
164
+ if (!this.capturing && !speaking) {
165
+ if (rms < this.base) this.base = this.base * 0.8 + rms * 0.2;
166
+ else if (rms < speakThr) this.base = this.base * 0.98 + rms * 0.02;
167
+ }
168
+
169
+ if (speaking) {
170
+ const thr = speakThr;
171
+ if (this.perfil.length < 40) this.perfil.push(rms);
172
+ // Only VOICE interrupts. A key click is loud but has no pitch.
173
+ const alto = rms > thr;
174
+ if (rms > this.maxEnquantoFala) this.maxEnquantoFala = rms;
175
+ const tom = alto ? Vad.periodicidade(chunk) : 0;
176
+ if (tom > this.tomDaInterrupcao) this.tomDaInterrupcao = tom;
177
+ if (tom >= Vad.bargeVozMin) this._vozHaMs = 0;
178
+ else this._vozHaMs += ms;
179
+ const ehVoz = alto && this._vozHaMs <= Vad.vozValeMs;
180
+ if (ehVoz) {
181
+ this.speechMs += ms;
182
+ this.quietMs = 0;
183
+ this._corrida += ms;
184
+ if (this._corrida > this._maiorCorrida) this._maiorCorrida = this._corrida;
185
+ if (this.speechMs >= Vad.bargeMs && this._maiorCorrida >= Vad.bargeRunMs) return VadStep.BARGE_IN;
186
+ } else {
187
+ this._corrida = 0;
188
+ this.quietMs += ms;
189
+ if (this.quietMs > Vad.bargeGapMs) {
190
+ this.speechMs = 0;
191
+ this.quietMs = 0;
192
+ this._maiorCorrida = 0;
193
+ }
194
+ }
195
+ return VadStep.IDLE;
196
+ }
197
+
198
+ if (rms > speakThr) {
199
+ this.capturing = true;
200
+ this.speechMs += ms;
201
+ this.quietMs = 0;
202
+ if (rms > this.picoDaFrase) this.picoDaFrase = rms;
203
+ const tf = Vad.periodicidade(chunk);
204
+ if (tf > this.tomDaFrase) this.tomDaFrase = tf;
205
+ } else if (this.capturing) {
206
+ if (rms < quietThr) this.quietMs += ms;
207
+ }
208
+ if (this.capturing) {
209
+ this._sum += rms;
210
+ if (rms < this._min) this._min = rms;
211
+ if (rms > this._max) this._max = rms;
212
+ this._n++;
213
+ }
214
+
215
+ if (!this.capturing) return VadStep.IDLE;
216
+
217
+ // Background noise caught early: seconds without a pause AND always at the same level.
218
+ const plano = this._min > 0 && this._max < this._min * Vad.flatRatio;
219
+ if (this.speechMs > Vad.noiseAfterMs && this.quietMs === 0 && plano) return this._noise();
220
+
221
+ if (this.quietMs <= Vad.quietToCloseMs && this.speechMs <= Vad.maxSpeechMs) return VadStep.CAPTURING;
222
+
223
+ const spoke = this.speechMs;
224
+ const nivel = this._n > 0 ? this._sum / this._n : 0;
225
+
226
+ // Fifteen seconds without ONE pause is not a person: it is constant noise.
227
+ if (spoke > Vad.maxSpeechMs && this.quietMs < 200) return this._noise();
228
+
229
+ return VadStep.done(spoke, spoke >= Vad.minSpeechMs, false, nivel);
230
+ }
231
+ }
232
+
233
+ /** Silence that closes a sentence (450 cut sentences, 900 was too slow; 700 is proven by the tests). */
234
+ Vad.quietToCloseMs = 700;
235
+ /** Minimum speech worth sending. Below this it is a cough or a door. */
236
+ Vad.minSpeechMs = 500;
237
+ /** Minimum recorded audio for the server to have something to hear. */
238
+ Vad.minAudioMs = 700;
239
+ /** Closes the sentence after this, even if the person goes on. */
240
+ Vad.maxSpeechMs = 15000;
241
+ /** VOICE time over her speech needed to silence her (two voiced slices). The pitch test does the heavy work. */
242
+ Vad.bargeMs = 130;
243
+ /** A pause long enough to give up an interruption (typing is ~5 keys a second: 200 ms apart). */
244
+ Vad.bargeGapMs = 130;
245
+ /** Continuous sound, without a single gap, so a loose slice does not count. */
246
+ Vad.bargeRunMs = 64;
247
+ /** How periodic a sound must be to count as voice (keyboard <= 0.20, human voice 0.50 to 0.93). */
248
+ Vad.bargeVozMin = 0.35;
249
+ /** How long the confidence lasts after the last voiced slice (the rest of the word counts). */
250
+ Vad.vozValeMs = 300;
251
+ /** Minimum level to count as an interruption, MEASURED LIVE (her echo 0.05, the person 0.12 to 0.25). Fixed. */
252
+ Vad.bargeFloor = 0.09;
253
+ /** Highest the LISTEN threshold can go, however noisy (without it she is deaf in a cafe). */
254
+ Vad.tetoOuvir = 0.1;
255
+ /** Highest level that can be taken as the room's silence. */
256
+ Vad.maxBase = 0.015;
257
+ /** Recording time without a pause after which we suspect it is noise. */
258
+ Vad.noiseAfterMs = 4000;
259
+ /** Voice goes up and down much more than this between chunks; background noise does not. */
260
+ Vad.flatRatio = 2.5;
261
+ /** Ceiling of the reference silence. */
262
+ Vad.maxNoiseBase = 0.12;
263
+
264
+ module.exports = { Vad, VadStep };