@livekit/agents-plugin-livekit 0.0.0-next-20260624041820

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.
Files changed (88) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +17 -0
  3. package/dist/hf_utils.cjs +272 -0
  4. package/dist/hf_utils.cjs.map +1 -0
  5. package/dist/hf_utils.d.cts +40 -0
  6. package/dist/hf_utils.d.ts +40 -0
  7. package/dist/hf_utils.d.ts.map +1 -0
  8. package/dist/hf_utils.js +237 -0
  9. package/dist/hf_utils.js.map +1 -0
  10. package/dist/hf_utils.test.cjs +330 -0
  11. package/dist/hf_utils.test.cjs.map +1 -0
  12. package/dist/hf_utils.test.d.cts +2 -0
  13. package/dist/hf_utils.test.d.ts +2 -0
  14. package/dist/hf_utils.test.d.ts.map +1 -0
  15. package/dist/hf_utils.test.js +307 -0
  16. package/dist/hf_utils.test.js.map +1 -0
  17. package/dist/index.cjs +63 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.cts +3 -0
  20. package/dist/index.d.ts +3 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +28 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/onnxruntime.d.cjs +2 -0
  25. package/dist/onnxruntime.d.cjs.map +1 -0
  26. package/dist/onnxruntime.d.js +1 -0
  27. package/dist/onnxruntime.d.js.map +1 -0
  28. package/dist/turn_detector/base.cjs +228 -0
  29. package/dist/turn_detector/base.cjs.map +1 -0
  30. package/dist/turn_detector/base.d.cts +54 -0
  31. package/dist/turn_detector/base.d.ts +54 -0
  32. package/dist/turn_detector/base.d.ts.map +1 -0
  33. package/dist/turn_detector/base.js +198 -0
  34. package/dist/turn_detector/base.js.map +1 -0
  35. package/dist/turn_detector/constants.cjs +44 -0
  36. package/dist/turn_detector/constants.cjs.map +1 -0
  37. package/dist/turn_detector/constants.d.cts +7 -0
  38. package/dist/turn_detector/constants.d.ts +7 -0
  39. package/dist/turn_detector/constants.d.ts.map +1 -0
  40. package/dist/turn_detector/constants.js +16 -0
  41. package/dist/turn_detector/constants.js.map +1 -0
  42. package/dist/turn_detector/english.cjs +52 -0
  43. package/dist/turn_detector/english.cjs.map +1 -0
  44. package/dist/turn_detector/english.d.cts +11 -0
  45. package/dist/turn_detector/english.d.ts +11 -0
  46. package/dist/turn_detector/english.d.ts.map +1 -0
  47. package/dist/turn_detector/english.js +26 -0
  48. package/dist/turn_detector/english.js.map +1 -0
  49. package/dist/turn_detector/index.cjs +58 -0
  50. package/dist/turn_detector/index.cjs.map +1 -0
  51. package/dist/turn_detector/index.d.cts +5 -0
  52. package/dist/turn_detector/index.d.ts +5 -0
  53. package/dist/turn_detector/index.d.ts.map +1 -0
  54. package/dist/turn_detector/index.js +28 -0
  55. package/dist/turn_detector/index.js.map +1 -0
  56. package/dist/turn_detector/multilingual.cjs +145 -0
  57. package/dist/turn_detector/multilingual.cjs.map +1 -0
  58. package/dist/turn_detector/multilingual.d.cts +15 -0
  59. package/dist/turn_detector/multilingual.d.ts +15 -0
  60. package/dist/turn_detector/multilingual.d.ts.map +1 -0
  61. package/dist/turn_detector/multilingual.js +119 -0
  62. package/dist/turn_detector/multilingual.js.map +1 -0
  63. package/dist/turn_detector/utils.cjs +54 -0
  64. package/dist/turn_detector/utils.cjs.map +1 -0
  65. package/dist/turn_detector/utils.d.cts +35 -0
  66. package/dist/turn_detector/utils.d.ts +35 -0
  67. package/dist/turn_detector/utils.d.ts.map +1 -0
  68. package/dist/turn_detector/utils.js +29 -0
  69. package/dist/turn_detector/utils.js.map +1 -0
  70. package/dist/turn_detector/utils.test.cjs +196 -0
  71. package/dist/turn_detector/utils.test.cjs.map +1 -0
  72. package/dist/turn_detector/utils.test.d.cts +2 -0
  73. package/dist/turn_detector/utils.test.d.ts +2 -0
  74. package/dist/turn_detector/utils.test.d.ts.map +1 -0
  75. package/dist/turn_detector/utils.test.js +195 -0
  76. package/dist/turn_detector/utils.test.js.map +1 -0
  77. package/package.json +51 -0
  78. package/src/hf_utils.test.ts +392 -0
  79. package/src/hf_utils.ts +365 -0
  80. package/src/index.ts +34 -0
  81. package/src/onnxruntime.d.ts +8 -0
  82. package/src/turn_detector/base.ts +268 -0
  83. package/src/turn_detector/constants.ts +16 -0
  84. package/src/turn_detector/english.ts +27 -0
  85. package/src/turn_detector/index.ts +31 -0
  86. package/src/turn_detector/multilingual.ts +147 -0
  87. package/src/turn_detector/utils.test.ts +231 -0
  88. package/src/turn_detector/utils.ts +76 -0
@@ -0,0 +1,27 @@
1
+ // SPDX-FileCopyrightText: 2025 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { EOUModel, EOURunnerBase } from './base.js';
5
+
6
+ export const INFERENCE_METHOD_EN = 'lk_end_of_utterance_en';
7
+
8
+ export class EOURunnerEn extends EOURunnerBase {
9
+ constructor() {
10
+ super('en');
11
+ }
12
+ }
13
+
14
+ export class EnglishModel extends EOUModel {
15
+ constructor(unlikelyThreshold?: number) {
16
+ super({
17
+ modelType: 'en',
18
+ unlikelyThreshold,
19
+ });
20
+ }
21
+
22
+ inferenceMethod(): string {
23
+ return INFERENCE_METHOD_EN;
24
+ }
25
+ }
26
+
27
+ export default EOURunnerEn;
@@ -0,0 +1,31 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { InferenceRunner } from '@livekit/agents';
5
+ import { extname } from 'node:path';
6
+ import { INFERENCE_METHOD_EN } from './english.js';
7
+ import { INFERENCE_METHOD_MULTILINGUAL } from './multilingual.js';
8
+
9
+ console.warn(
10
+ 'The text-based turn detector from @livekit/agents-plugin-livekit is deprecated. ' +
11
+ 'The audio EOT detector in `@livekit/agents` inference (TurnDetector) replaces ' +
12
+ 'it and runs natively on-device via @livekit/local-inference. ' +
13
+ 'This text-based path will be removed in a future release.',
14
+ );
15
+
16
+ export { EOUModel } from './base.js';
17
+ export { EnglishModel } from './english.js';
18
+ export { MultilingualModel } from './multilingual.js';
19
+ export { getUnicodeCategory, normalizeText } from './utils.js';
20
+
21
+ const currentFileExtension = extname(import.meta.url);
22
+
23
+ InferenceRunner.registerRunner(
24
+ INFERENCE_METHOD_EN,
25
+ new URL(`./english${currentFileExtension}`, import.meta.url).toString(),
26
+ );
27
+
28
+ InferenceRunner.registerRunner(
29
+ INFERENCE_METHOD_MULTILINGUAL,
30
+ new URL(`./multilingual${currentFileExtension}`, import.meta.url).toString(),
31
+ );
@@ -0,0 +1,147 @@
1
+ // SPDX-FileCopyrightText: 2025 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import type { llm } from '@livekit/agents';
5
+ import { getJobContext, log, normalizeLanguage } from '@livekit/agents';
6
+ import { EOUModel, EOURunnerBase } from './base.js';
7
+ import { MAX_HISTORY_TURNS } from './constants.js';
8
+
9
+ const REMOTE_INFERENCE_TIMEOUT = 2000;
10
+
11
+ export const INFERENCE_METHOD_MULTILINGUAL = 'lk_end_of_utterance_multilingual';
12
+
13
+ export class EUORunnerMultilingual extends EOURunnerBase {
14
+ constructor() {
15
+ super('multilingual');
16
+ }
17
+ }
18
+
19
+ export class MultilingualModel extends EOUModel {
20
+ #logger = log();
21
+
22
+ constructor(unlikelyThreshold?: number) {
23
+ super({
24
+ modelType: 'multilingual',
25
+ unlikelyThreshold,
26
+ });
27
+ }
28
+
29
+ inferenceMethod(): string {
30
+ return INFERENCE_METHOD_MULTILINGUAL;
31
+ }
32
+
33
+ async unlikelyThreshold(language?: string): Promise<number | undefined> {
34
+ if (!language) {
35
+ return undefined;
36
+ }
37
+
38
+ language = normalizeLanguage(language);
39
+
40
+ let threshold = await super.unlikelyThreshold(language);
41
+ if (threshold === undefined) {
42
+ const url = remoteInferenceUrl();
43
+ if (!url) return undefined;
44
+
45
+ const resp = await fetch(url, {
46
+ method: 'POST',
47
+ body: JSON.stringify({
48
+ language,
49
+ }),
50
+ headers: {
51
+ 'Content-Type': 'application/json',
52
+ },
53
+ signal: AbortSignal.timeout(REMOTE_INFERENCE_TIMEOUT),
54
+ });
55
+
56
+ if (!resp.ok) {
57
+ throw new Error(`Failed to fetch threshold: ${resp.statusText}`);
58
+ }
59
+
60
+ const data = (await resp.json()) as { threshold: number | undefined };
61
+ threshold = data.threshold;
62
+ if (threshold) {
63
+ const languages = await this.languagesFuture.await;
64
+ languages[language] = { threshold };
65
+ }
66
+ }
67
+
68
+ return threshold;
69
+ }
70
+
71
+ async predictEndOfTurn(chatCtx: llm.ChatContext, timeoutMs?: number): Promise<number> {
72
+ const url = remoteInferenceUrl();
73
+ if (!url) {
74
+ return await super.predictEndOfTurn(chatCtx, timeoutMs);
75
+ }
76
+
77
+ // Copy and process chat context similar to Python implementation
78
+ const messages = chatCtx
79
+ .copy({
80
+ excludeFunctionCall: true,
81
+ excludeInstructions: true,
82
+ excludeEmptyMessage: true,
83
+ })
84
+ .truncate(MAX_HISTORY_TURNS);
85
+
86
+ // Get job context and build request
87
+ const ctx = getJobContext();
88
+ const request: any = {
89
+ ...messages.toJSON({
90
+ excludeImage: true,
91
+ excludeAudio: true,
92
+ excludeTimestamp: true,
93
+ }),
94
+ jobId: ctx.job.id,
95
+ workerId: ctx.workerId,
96
+ };
97
+
98
+ // Add agentId from environment variable if available
99
+ const agentId = process.env.LIVEKIT_AGENT_ID;
100
+ if (agentId) {
101
+ request.agentId = agentId;
102
+ }
103
+
104
+ const startedAt = performance.now();
105
+
106
+ this.#logger.debug({ url, request }, '=== remote EOU inference');
107
+
108
+ const resp = await fetch(url, {
109
+ method: 'POST',
110
+ body: JSON.stringify(request),
111
+ headers: {
112
+ 'Content-Type': 'application/json',
113
+ },
114
+ signal: AbortSignal.timeout(REMOTE_INFERENCE_TIMEOUT),
115
+ });
116
+
117
+ if (!resp.ok) {
118
+ throw new Error(`Failed to predict end of turn: ${resp.statusText}`);
119
+ }
120
+
121
+ const data = await resp.json();
122
+ const probability = data.probability;
123
+ if (typeof probability === 'number' && probability >= 0) {
124
+ this.#logger.debug(
125
+ {
126
+ eouProbability: probability,
127
+ duration: (performance.now() - startedAt) / 1000,
128
+ },
129
+ 'eou prediction',
130
+ );
131
+ return probability;
132
+ }
133
+
134
+ // default to indicate no prediction
135
+ return 1;
136
+ }
137
+ }
138
+
139
+ function remoteInferenceUrl() {
140
+ const urlBase = process.env.LIVEKIT_REMOTE_EOT_URL;
141
+ if (!urlBase) {
142
+ return undefined;
143
+ }
144
+ return `${urlBase}/eot/multi`;
145
+ }
146
+
147
+ export default EUORunnerMultilingual;
@@ -0,0 +1,231 @@
1
+ // SPDX-FileCopyrightText: 2025 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { describe, expect, it } from 'vitest';
5
+ import { getUnicodeCategory, normalizeText } from './utils.js';
6
+
7
+ describe('getUnicodeCategory', () => {
8
+ it('should identify basic ASCII punctuation', () => {
9
+ expect(getUnicodeCategory('!')).toBe('P');
10
+ expect(getUnicodeCategory('"')).toBe('P');
11
+ expect(getUnicodeCategory('#')).toBe('P');
12
+ expect(getUnicodeCategory('$')).toBe('P');
13
+ expect(getUnicodeCategory('%')).toBe('P');
14
+ expect(getUnicodeCategory('&')).toBe('P');
15
+ expect(getUnicodeCategory("'")).toBe('P');
16
+ expect(getUnicodeCategory('(')).toBe('P');
17
+ expect(getUnicodeCategory(')')).toBe('P');
18
+ expect(getUnicodeCategory('*')).toBe('P');
19
+ expect(getUnicodeCategory('+')).toBe('P');
20
+ expect(getUnicodeCategory(',')).toBe('P');
21
+ expect(getUnicodeCategory('-')).toBe('P');
22
+ expect(getUnicodeCategory('.')).toBe('P');
23
+ expect(getUnicodeCategory('/')).toBe('P');
24
+ });
25
+
26
+ it('should identify colon/semicolon punctuation', () => {
27
+ expect(getUnicodeCategory(':')).toBe('P');
28
+ expect(getUnicodeCategory(';')).toBe('P');
29
+ expect(getUnicodeCategory('<')).toBe('P');
30
+ expect(getUnicodeCategory('=')).toBe('P');
31
+ expect(getUnicodeCategory('>')).toBe('P');
32
+ expect(getUnicodeCategory('?')).toBe('P');
33
+ expect(getUnicodeCategory('@')).toBe('P');
34
+ });
35
+
36
+ it('should identify bracket punctuation', () => {
37
+ expect(getUnicodeCategory('[')).toBe('P');
38
+ expect(getUnicodeCategory('\\')).toBe('P');
39
+ expect(getUnicodeCategory(']')).toBe('P');
40
+ expect(getUnicodeCategory('^')).toBe('P');
41
+ expect(getUnicodeCategory('_')).toBe('P');
42
+ expect(getUnicodeCategory('`')).toBe('P');
43
+ });
44
+
45
+ it('should identify brace punctuation', () => {
46
+ expect(getUnicodeCategory('{')).toBe('P');
47
+ expect(getUnicodeCategory('|')).toBe('P');
48
+ expect(getUnicodeCategory('}')).toBe('P');
49
+ expect(getUnicodeCategory('~')).toBe('P');
50
+ });
51
+
52
+ it('should identify extended punctuation', () => {
53
+ expect(getUnicodeCategory('¡')).toBe('P');
54
+ expect(getUnicodeCategory('¿')).toBe('P');
55
+ expect(getUnicodeCategory('«')).toBe('P');
56
+ expect(getUnicodeCategory('»')).toBe('P');
57
+ });
58
+
59
+ it('should not identify letters as punctuation', () => {
60
+ expect(getUnicodeCategory('a')).toBe('');
61
+ expect(getUnicodeCategory('A')).toBe('');
62
+ expect(getUnicodeCategory('z')).toBe('');
63
+ expect(getUnicodeCategory('Z')).toBe('');
64
+ });
65
+
66
+ it('should not identify numbers as punctuation', () => {
67
+ expect(getUnicodeCategory('0')).toBe('');
68
+ expect(getUnicodeCategory('1')).toBe('');
69
+ expect(getUnicodeCategory('9')).toBe('');
70
+ });
71
+
72
+ it('should not identify whitespace as punctuation', () => {
73
+ expect(getUnicodeCategory(' ')).toBe('');
74
+ expect(getUnicodeCategory('\t')).toBe('');
75
+ expect(getUnicodeCategory('\n')).toBe('');
76
+ });
77
+
78
+ it('should handle empty string', () => {
79
+ expect(getUnicodeCategory('')).toBe('');
80
+ });
81
+
82
+ it('should handle unicode characters', () => {
83
+ expect(getUnicodeCategory('é')).toBe('');
84
+ expect(getUnicodeCategory('ñ')).toBe('');
85
+ expect(getUnicodeCategory('ç')).toBe('');
86
+ });
87
+ });
88
+
89
+ describe('normalizeText', () => {
90
+ describe('basic functionality', () => {
91
+ it('should convert to lowercase', () => {
92
+ expect(normalizeText('HELLO')).toBe('hello');
93
+ expect(normalizeText('HeLLo')).toBe('hello');
94
+ expect(normalizeText('WORLD')).toBe('world');
95
+ });
96
+
97
+ it('should remove basic punctuation', () => {
98
+ expect(normalizeText('Hello!')).toBe('hello');
99
+ expect(normalizeText('Hello?')).toBe('hello');
100
+ expect(normalizeText('Hello.')).toBe('hello');
101
+ expect(normalizeText('Hello,')).toBe('hello');
102
+ });
103
+
104
+ it('should preserve apostrophes', () => {
105
+ expect(normalizeText("I'm happy")).toBe("i'm happy");
106
+ expect(normalizeText("don't worry")).toBe("don't worry");
107
+ expect(normalizeText("it's great")).toBe("it's great");
108
+ });
109
+
110
+ it('should preserve hyphens', () => {
111
+ expect(normalizeText('well-trained')).toBe('well-trained');
112
+ expect(normalizeText('state-of-the-art')).toBe('state-of-the-art');
113
+ expect(normalizeText('co-worker')).toBe('co-worker');
114
+ });
115
+
116
+ it('should collapse multiple whitespace', () => {
117
+ expect(normalizeText('hello world')).toBe('hello world');
118
+ expect(normalizeText('multiple spaces here')).toBe('multiple spaces here');
119
+ expect(normalizeText('tab\t\tspaces')).toBe('tab spaces');
120
+ expect(normalizeText('newline\n\nspaces')).toBe('newline spaces');
121
+ });
122
+
123
+ it('should trim leading and trailing whitespace', () => {
124
+ expect(normalizeText(' hello ')).toBe('hello');
125
+ expect(normalizeText('\t\nhello\t\n')).toBe('hello');
126
+ expect(normalizeText(' hello world ')).toBe('hello world');
127
+ });
128
+ });
129
+
130
+ describe('comprehensive test cases', () => {
131
+ it('should handle the basic greeting case', () => {
132
+ expect(normalizeText('Hi, how can I help you today?')).toBe('hi how can i help you today');
133
+ });
134
+
135
+ it('should handle contractions and hyphens', () => {
136
+ expect(normalizeText("I'm a well-trained assistant!")).toBe("i'm a well-trained assistant");
137
+ });
138
+
139
+ it('should remove various punctuation types', () => {
140
+ expect(normalizeText('Hello!!! What??? Price: $19.99 (20% off).')).toBe(
141
+ 'hello what price 1999 20 off',
142
+ );
143
+ });
144
+
145
+ it('should handle multiple spaces', () => {
146
+ expect(normalizeText('Multiple spaces here')).toBe('multiple spaces here');
147
+ });
148
+
149
+ it('should handle unicode characters', () => {
150
+ expect(normalizeText('Café entrées naïve résumé')).toBe('café entrées naïve résumé');
151
+ });
152
+
153
+ it('should handle mixed punctuation and unicode', () => {
154
+ expect(normalizeText('¿Cómo estás? ¡Muy bien!')).toBe('cómo estás muy bien');
155
+ });
156
+ });
157
+
158
+ describe('edge cases', () => {
159
+ it('should handle empty string', () => {
160
+ expect(normalizeText('')).toBe('');
161
+ });
162
+
163
+ it('should handle whitespace-only string', () => {
164
+ expect(normalizeText(' ')).toBe('');
165
+ expect(normalizeText('\t\n ')).toBe('');
166
+ });
167
+
168
+ it('should handle punctuation-only string', () => {
169
+ expect(normalizeText('!!!')).toBe('');
170
+ expect(normalizeText('???')).toBe('');
171
+ expect(normalizeText('...')).toBe('');
172
+ });
173
+
174
+ it('should handle mixed punctuation and preserved characters', () => {
175
+ expect(normalizeText('!@#$%^&*()_+-={}[]|\\:;"\'<>?,./')).toBe("-'");
176
+ });
177
+
178
+ it('should handle numbers with punctuation', () => {
179
+ expect(normalizeText('$19.99')).toBe('1999');
180
+ expect(normalizeText('(555) 123-4567')).toBe('555 123-4567');
181
+ });
182
+
183
+ it('should handle special unicode punctuation', () => {
184
+ expect(normalizeText('Hello… world!')).toBe('hello world');
185
+ expect(normalizeText('"Quoted text"')).toBe('quoted text');
186
+ expect(normalizeText("'Single quotes'")).toBe("'single quotes'");
187
+ });
188
+ });
189
+
190
+ describe('unicode normalization', () => {
191
+ it('should apply NFKC normalization', () => {
192
+ expect(normalizeText('café')).toBe('café');
193
+ expect(normalizeText('naïve')).toBe('naïve');
194
+ });
195
+
196
+ it('should handle combining characters', () => {
197
+ const eWithCombiningAcute = 'caf\u0065\u0301';
198
+ const precomposedE = 'café';
199
+ expect(normalizeText(eWithCombiningAcute)).toBe(normalizeText(precomposedE));
200
+ });
201
+ });
202
+
203
+ describe('real-world examples', () => {
204
+ it('should handle typical assistant responses', () => {
205
+ expect(normalizeText('Hello! How can I assist you today?')).toBe(
206
+ 'hello how can i assist you today',
207
+ );
208
+ expect(normalizeText("I'm here to help with any questions you might have.")).toBe(
209
+ "i'm here to help with any questions you might have",
210
+ );
211
+ });
212
+
213
+ it('should handle typical user queries', () => {
214
+ expect(normalizeText("What's the weather like?")).toBe("what's the weather like");
215
+ expect(normalizeText('Can you help me with my order?')).toBe('can you help me with my order');
216
+ expect(normalizeText('I need assistance, please!')).toBe('i need assistance please');
217
+ });
218
+
219
+ it('should handle incomplete sentences', () => {
220
+ expect(normalizeText('What is the weather in')).toBe('what is the weather in');
221
+ expect(normalizeText('I am looking for')).toBe('i am looking for');
222
+ expect(normalizeText('Could you please')).toBe('could you please');
223
+ });
224
+
225
+ it('should handle multilingual text', () => {
226
+ expect(normalizeText('Bonjour! Comment ça va?')).toBe('bonjour comment ça va');
227
+ expect(normalizeText('¡Hola! ¿Cómo estás?')).toBe('hola cómo estás');
228
+ expect(normalizeText('Guten Tag! Wie geht es Ihnen?')).toBe('guten tag wie geht es ihnen');
229
+ });
230
+ });
231
+ });
@@ -0,0 +1,76 @@
1
+ // SPDX-FileCopyrightText: 2025 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+
5
+ /**
6
+ * Text normalization utilities for EOU turn detector
7
+ */
8
+
9
+ /**
10
+ * Simple unicode category detection for punctuation
11
+ * Mimics Python's unicodedata.category() for punctuation detection
12
+ */
13
+ export function getUnicodeCategory(char: string): string {
14
+ const code = char.codePointAt(0);
15
+ if (!code) return '';
16
+
17
+ // Basic punctuation ranges (simplified version to match Python unicodedata.category)
18
+ if (
19
+ (code >= 0x21 && code <= 0x2f) || // !"#$%&'()*+,-./
20
+ (code >= 0x3a && code <= 0x40) || // :;<=>?@
21
+ (code >= 0x5b && code <= 0x60) || // [\]^_`
22
+ (code >= 0x7b && code <= 0x7e) || // {|}~
23
+ (code >= 0xa0 && code <= 0xbf) || // Latin-1 punctuation
24
+ (code >= 0x2000 && code <= 0x206f) || // General punctuation
25
+ (code >= 0x3000 && code <= 0x303f)
26
+ ) {
27
+ // CJK symbols and punctuation
28
+ return 'P';
29
+ }
30
+ return '';
31
+ }
32
+
33
+ /**
34
+ * Normalizes text to match the training data format used by the EOU model
35
+ *
36
+ * This function applies the following transformations:
37
+ * 1. Converts to lowercase
38
+ * 2. Applies Unicode NFKC normalization
39
+ * 3. Removes all punctuation except apostrophes (') and hyphens (-)
40
+ * 4. Collapses multiple whitespace characters into single spaces
41
+ * 5. Trims leading and trailing whitespace
42
+ *
43
+ * @param text - The input text to normalize
44
+ * @returns The normalized text
45
+ *
46
+ * @example
47
+ * ```typescript
48
+ * normalizeText("Hi, how can I help you today?")
49
+ * // Returns: "hi how can i help you today"
50
+ *
51
+ * normalizeText("I'm a well-trained assistant!")
52
+ * // Returns: "i'm a well-trained assistant"
53
+ *
54
+ * normalizeText("Price: $19.99 (20% off).")
55
+ * // Returns: "price 1999 20 off"
56
+ * ```
57
+ */
58
+ export function normalizeText(text: string): string {
59
+ if (!text) return '';
60
+
61
+ let normalized = text.toLowerCase().normalize('NFKC');
62
+
63
+ // Remove punctuation except apostrophes and hyphens
64
+ // Using character-by-character approach to match Python logic
65
+ normalized = Array.from(normalized)
66
+ .filter((ch) => {
67
+ const category = getUnicodeCategory(ch);
68
+ return !(category.startsWith('P') && ch !== "'" && ch !== '-');
69
+ })
70
+ .join('');
71
+
72
+ // Collapse whitespace and trim
73
+ normalized = normalized.replace(/\s+/g, ' ').trim();
74
+
75
+ return normalized;
76
+ }