pyannote-cpp-node 0.1.0 → 0.2.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/README.md CHANGED
@@ -1,43 +1,44 @@
1
1
  # pyannote-cpp-node
2
2
 
3
- Node.js native bindings for real-time speaker diarization
4
-
5
3
  ![Platform](https://img.shields.io/badge/platform-macOS-lightgrey)
6
4
  ![Node](https://img.shields.io/badge/node-%3E%3D18-brightgreen)
7
5
 
6
+ Node.js native bindings for integrated Whisper transcription + speaker diarization with speaker-labeled segment output.
7
+
8
8
  ## Overview
9
9
 
10
- `pyannote-cpp-node` provides Node.js bindings to a high-performance C++ port of the [`pyannote/speaker-diarization-community-1`](https://huggingface.co/pyannote/speaker-diarization-community-1) pipeline. It achieves **39x real-time** performance on Apple Silicon by leveraging CoreML acceleration (Neural Engine + GPU) for neural network inference and optimized C++ implementations of clustering algorithms.
10
+ `pyannote-cpp-node` exposes the integrated C++ pipeline that combines streaming diarization and Whisper transcription into a single API.
11
11
 
12
- The library supports two modes:
12
+ Given 16 kHz mono PCM audio (`Float32Array`), it produces cumulative and final transcript segments shaped as:
13
13
 
14
- - **Offline diarization**: Process an entire audio file at once and receive speaker-labeled segments
15
- - **Streaming diarization**: Process audio incrementally in real-time, receive voice activity detection (VAD) as audio arrives, and trigger speaker clustering on demand
14
+ - speaker label (`SPEAKER_00`, `SPEAKER_01`, ...)
15
+ - segment start/duration in seconds
16
+ - segment text
16
17
 
17
- All heavy operations are asynchronous and run on libuv worker threads, ensuring the Node.js event loop remains responsive.
18
+ The API supports both one-shot processing (`transcribe`) and incremental streaming (`createSession` + `push`/`finalize`). All heavy operations are asynchronous and run on libuv worker threads.
18
19
 
19
20
  ## Features
20
21
 
21
- - **Offline diarization** Process full audio files and get speaker-labeled segments
22
- - **Streaming diarization** Push audio incrementally, receive real-time VAD, recluster on demand
23
- - **Async/await API** All heavy operations return Promises and run on worker threads
24
- - **CoreML acceleration** Neural networks run on Apple's Neural Engine, GPU, and CPU
25
- - **TypeScript-first** Full type definitions included
26
- - **Zero-copy audio input** — Direct `Float32Array` input for maximum efficiency
27
- - **Byte-identical output** Streaming finalize produces identical results to offline pipeline
22
+ - Integrated transcription + diarization in one pipeline
23
+ - Speaker-labeled transcript segments with sentence-level text
24
+ - One-shot and streaming APIs with the same output schema
25
+ - Incremental `segments` events for live applications
26
+ - Deterministic output for the same audio/models/config
27
+ - CoreML-accelerated inference on macOS
28
+ - TypeScript-first API with complete type definitions
28
29
 
29
30
  ## Requirements
30
31
 
31
- - **macOS** with Apple Silicon (M1/M2/M3/M4) or Intel x64
32
- - **Node.js** >= 18
33
- - **Model files**:
34
- - Segmentation GGUF model (`segmentation.gguf`)
35
- - Embedding GGUF model (`embedding.gguf`)
36
- - PLDA GGUF model (`plda.gguf`)
37
- - Segmentation CoreML model package (`segmentation.mlpackage/`)
38
- - Embedding CoreML model package (`embedding.mlpackage/`)
39
-
40
- Model files can be obtained by converting the original PyTorch models using the conversion scripts in the parent repository.
32
+ - macOS (Apple Silicon or Intel)
33
+ - Node.js >= 18
34
+ - Model files:
35
+ - Segmentation GGUF (`segModelPath`)
36
+ - Embedding GGUF (`embModelPath`)
37
+ - PLDA GGUF (`pldaPath`)
38
+ - Embedding CoreML `.mlpackage` (`coremlPath`)
39
+ - Segmentation CoreML `.mlpackage` (`segCoremlPath`)
40
+ - Whisper GGUF (`whisperModelPath`)
41
+ - Optional Silero VAD model (`vadModelPath`)
41
42
 
42
43
  ## Installation
43
44
 
@@ -45,721 +46,403 @@ Model files can be obtained by converting the original PyTorch models using the
45
46
  npm install pyannote-cpp-node
46
47
  ```
47
48
 
48
- Or with pnpm:
49
-
50
49
  ```bash
51
50
  pnpm add pyannote-cpp-node
52
51
  ```
53
52
 
54
- The package uses `optionalDependencies` to automatically install the correct platform-specific native addon (`@pyannote-cpp-node/darwin-arm64` or `@pyannote-cpp-node/darwin-x64`).
53
+ The package installs a platform-specific native addon through `optionalDependencies`.
55
54
 
56
55
  ## Quick Start
57
56
 
58
57
  ```typescript
59
- import { Pyannote } from 'pyannote-cpp-node';
60
- import { readFileSync } from 'node:fs';
58
+ import { Pipeline } from 'pyannote-cpp-node';
61
59
 
62
- // Load model (validates all paths exist)
63
- const model = await Pyannote.load({
60
+ const pipeline = await Pipeline.load({
64
61
  segModelPath: './models/segmentation.gguf',
65
62
  embModelPath: './models/embedding.gguf',
66
63
  pldaPath: './models/plda.gguf',
67
64
  coremlPath: './models/embedding.mlpackage',
68
65
  segCoremlPath: './models/segmentation.mlpackage',
66
+ whisperModelPath: './models/ggml-large-v3-turbo-q5_0.bin',
67
+ language: 'en',
69
68
  });
70
69
 
71
- // Load audio (16kHz mono Float32Array - see "Audio Format Requirements")
72
- const audio = loadWavFile('./audio.wav');
73
-
74
- // Run diarization
75
- const result = await model.diarize(audio);
70
+ const audio = loadAudioAsFloat32Array('./audio-16khz-mono.wav');
71
+ const result = await pipeline.transcribe(audio);
76
72
 
77
- // Print results
78
73
  for (const segment of result.segments) {
74
+ const end = segment.start + segment.duration;
79
75
  console.log(
80
- `[${segment.start.toFixed(2)}s - ${(segment.start + segment.duration).toFixed(2)}s] ${segment.speaker}`
76
+ `[${segment.speaker}] ${segment.start.toFixed(2)}-${end.toFixed(2)} ${segment.text.trim()}`
81
77
  );
82
78
  }
83
79
 
84
- // Clean up
85
- model.close();
80
+ pipeline.close();
86
81
  ```
87
82
 
88
83
  ## API Reference
89
84
 
90
- ### `Pyannote` Class
91
-
92
- The main entry point for loading diarization models.
85
+ ### `Pipeline`
93
86
 
94
- #### `static async load(config: ModelConfig): Promise<Pyannote>`
95
-
96
- Factory method for loading a diarization model. Validates that all model paths exist before initializing. CoreML model compilation happens synchronously during initialization and is typically fast.
97
-
98
- **Parameters:**
99
- - `config: ModelConfig` — Configuration object with paths to all required model files
100
-
101
- **Returns:** `Promise<Pyannote>` — Initialized model instance
102
-
103
- **Throws:**
104
- - `Error` if any model path does not exist or is invalid
105
-
106
- **Example:**
107
87
  ```typescript
108
- const model = await Pyannote.load({
109
- segModelPath: './models/segmentation.gguf',
110
- embModelPath: './models/embedding.gguf',
111
- pldaPath: './models/plda.gguf',
112
- coremlPath: './models/embedding.mlpackage',
113
- segCoremlPath: './models/segmentation.mlpackage',
114
- });
88
+ class Pipeline {
89
+ static async load(config: ModelConfig): Promise<Pipeline>;
90
+ async transcribe(audio: Float32Array): Promise<TranscriptionResult>;
91
+ createSession(): PipelineSession;
92
+ close(): void;
93
+ get isClosed(): boolean;
94
+ }
115
95
  ```
116
96
 
117
- #### `async diarize(audio: Float32Array): Promise<DiarizationResult>`
97
+ #### `static async load(config: ModelConfig): Promise<Pipeline>`
118
98
 
119
- Performs offline diarization on the entire audio file. Audio must be 16kHz mono in `Float32Array` format with values in the range [-1.0, 1.0].
99
+ Validates model paths and initializes native pipeline resources.
120
100
 
121
- Internally, this method uses the streaming API: it initializes a streaming session, pushes all audio in 1-second chunks, calls finalize, and cleans up. The operation runs on a worker thread and is non-blocking.
101
+ #### `async transcribe(audio: Float32Array): Promise<TranscriptionResult>`
122
102
 
123
- **Parameters:**
124
- - `audio: Float32Array` — Audio samples (16kHz mono, values in [-1.0, 1.0])
103
+ Runs one-shot transcription + diarization on the full audio buffer.
125
104
 
126
- **Returns:** `Promise<DiarizationResult>` — Diarization result with speaker-labeled segments sorted by start time
105
+ #### `createSession(): PipelineSession`
127
106
 
128
- **Throws:**
129
- - `Error` if model is closed
130
- - `TypeError` if audio is not a `Float32Array`
131
- - `Error` if audio is empty
107
+ Creates an independent streaming session for incremental processing.
132
108
 
133
- **Example:**
134
- ```typescript
135
- const result = await model.diarize(audio);
136
- console.log(`Detected ${result.segments.length} segments`);
137
- ```
109
+ #### `close(): void`
138
110
 
139
- #### `createStreamingSession(): StreamingSession`
111
+ Releases native resources. Safe to call multiple times.
140
112
 
141
- Creates a new independent streaming session. Each session maintains its own internal state and can be used to process audio incrementally.
113
+ #### `get isClosed(): boolean`
142
114
 
143
- **Returns:** `StreamingSession` New streaming session instance
115
+ Returns `true` after `close()`.
144
116
 
145
- **Throws:**
146
- - `Error` if model is closed
117
+ ### `PipelineSession` (extends `EventEmitter`)
147
118
 
148
- **Example:**
149
119
  ```typescript
150
- const session = model.createStreamingSession();
120
+ class PipelineSession extends EventEmitter {
121
+ async push(audio: Float32Array): Promise<boolean[]>;
122
+ async finalize(): Promise<TranscriptionResult>;
123
+ close(): void;
124
+ get isClosed(): boolean;
125
+ // Event: 'segments' -> (segments: AlignedSegment[], audio: Float32Array)
126
+ }
151
127
  ```
152
128
 
153
- #### `close(): void`
154
-
155
- Releases all native resources associated with the model. This method is idempotent and safe to call multiple times.
156
-
157
- Once closed, the model cannot be used for diarization or creating new streaming sessions. Existing streaming sessions should be closed before closing the model.
158
-
159
- **Example:**
160
- ```typescript
161
- model.close();
162
- console.log(model.isClosed); // true
163
- ```
129
+ #### `async push(audio: Float32Array): Promise<boolean[]>`
164
130
 
165
- #### `get isClosed: boolean`
131
+ Pushes an arbitrary number of samples into the streaming pipeline.
166
132
 
167
- Indicates whether the model has been closed.
133
+ - Return value is per-frame VAD booleans (`true` = speech, `false` = silence)
134
+ - First 10 seconds return an empty array because the pipeline needs a full 10-second window
135
+ - Chunk size is flexible; not restricted to 16,000-sample pushes
168
136
 
169
- **Returns:** `boolean` `true` if the model is closed, `false` otherwise
137
+ #### `async finalize(): Promise<TranscriptionResult>`
170
138
 
171
- ### `StreamingSession` Class
139
+ Flushes all stages, runs final recluster + alignment, and returns the definitive result.
172
140
 
173
- Handles incremental audio processing for real-time diarization.
141
+ #### `close(): void`
174
142
 
175
- #### `async push(audio: Float32Array): Promise<VADChunk[]>`
143
+ Releases native session resources. Safe to call multiple times.
176
144
 
177
- Pushes audio samples to the streaming session. Audio must be 16kHz mono `Float32Array`. Typically, push 1 second of audio (16,000 samples) at a time.
145
+ #### `get isClosed(): boolean`
178
146
 
179
- The first chunk requires 10 seconds of accumulated audio to produce output (the segmentation model uses a 10-second window). After that, each subsequent push returns approximately one `VADChunk` (depending on the 1-second hop size).
147
+ Returns `true` after `close()`.
180
148
 
181
- The returned VAD chunks contain frame-level voice activity (OR of all speakers) for the newly processed 10-second windows.
149
+ #### Event: `'segments'`
182
150
 
183
- **Parameters:**
184
- - `audio: Float32Array` — Audio samples (16kHz mono, values in [-1.0, 1.0])
151
+ Emitted after each Whisper transcription result with the latest cumulative aligned output.
185
152
 
186
- **Returns:** `Promise<VADChunk[]>` — Array of VAD chunks (empty until 10 seconds accumulated)
153
+ ```typescript
154
+ session.on('segments', (segments: AlignedSegment[], audio: Float32Array) => {
155
+ // `segments` contains the latest cumulative speaker-labeled transcript
156
+ // `audio` contains the chunk submitted for this callback cycle
157
+ });
158
+ ```
187
159
 
188
- **Throws:**
189
- - `Error` if session is closed
190
- - `TypeError` if audio is not a `Float32Array`
160
+ ### Types
191
161
 
192
- **Example:**
193
162
  ```typescript
194
- const vadChunks = await session.push(audioChunk);
195
- for (const chunk of vadChunks) {
196
- console.log(`VAD chunk ${chunk.chunkIndex}: ${chunk.numFrames} frames`);
197
- }
198
- ```
163
+ export interface ModelConfig {
164
+ // === Required Model Paths ===
165
+ /** Path to segmentation GGUF model */
166
+ segModelPath: string;
199
167
 
200
- #### `async recluster(): Promise<DiarizationResult>`
168
+ /** Path to embedding GGUF model */
169
+ embModelPath: string;
201
170
 
202
- Triggers full clustering on all accumulated audio data. This runs the complete diarization pipeline (embedding extraction → PLDA scoring hierarchical clustering → VBx refinement → speaker assignment) and returns speaker-labeled segments with global speaker IDs.
171
+ /** Path to PLDA GGUF model */
172
+ pldaPath: string;
203
173
 
204
- **Warning:** This method mutates the internal session state. Specifically, it replaces the internal embedding and chunk index arrays with filtered versions (excluding silent speakers). Calling `push` after `recluster` may produce unexpected results. Use `recluster` sparingly (e.g., every 30 seconds for live progress updates) or only call `finalize` when the stream ends.
174
+ /** Path to embedding CoreML .mlpackage directory */
175
+ coremlPath: string;
205
176
 
206
- The operation runs on a worker thread and is non-blocking.
177
+ /** Path to segmentation CoreML .mlpackage directory */
178
+ segCoremlPath: string;
207
179
 
208
- **Returns:** `Promise<DiarizationResult>` Complete diarization result with global speaker labels
180
+ /** Path to Whisper GGUF model */
181
+ whisperModelPath: string;
209
182
 
210
- **Throws:**
211
- - `Error` if session is closed
183
+ // === Optional Model Paths ===
184
+ /** Path to Silero VAD model (optional, enables silence compression) */
185
+ vadModelPath?: string;
212
186
 
213
- **Example:**
214
- ```typescript
215
- // Trigger intermediate clustering after accumulating data
216
- const intermediateResult = await session.recluster();
217
- console.log(`Current speaker count: ${new Set(intermediateResult.segments.map(s => s.speaker)).size}`);
218
- ```
187
+ // === Whisper Context Options (model loading) ===
188
+ /** Enable GPU acceleration (default: true) */
189
+ useGpu?: boolean;
219
190
 
220
- #### `async finalize(): Promise<DiarizationResult>`
191
+ /** Enable Flash Attention (default: true) */
192
+ flashAttn?: boolean;
221
193
 
222
- Processes any remaining audio (zero-padding partial chunks to match the offline pipeline's chunk count formula), then performs final clustering. This method produces byte-identical output to the offline `diarize()` method when given the same input audio.
194
+ /** GPU device index (default: 0) */
195
+ gpuDevice?: number;
223
196
 
224
- Call this method when the audio stream has ended to get the final diarization result.
197
+ /**
198
+ * Enable CoreML acceleration for Whisper encoder on macOS (default: false).
199
+ * The CoreML model must be placed next to the GGUF model with naming convention:
200
+ * e.g., ggml-base.en.bin -> ggml-base.en-encoder.mlmodelc/
201
+ */
202
+ useCoreml?: boolean;
225
203
 
226
- The operation runs on a worker thread and is non-blocking.
204
+ /** Suppress whisper.cpp log output (default: false) */
205
+ noPrints?: boolean;
227
206
 
228
- **Returns:** `Promise<DiarizationResult>` Final diarization result
207
+ // === Whisper Decode Options ===
208
+ /** Number of threads for Whisper inference (default: 4) */
209
+ nThreads?: number;
229
210
 
230
- **Throws:**
231
- - `Error` if session is closed
211
+ /** Language code (e.g., 'en', 'zh'). Omit for auto-detect. (default: 'en') */
212
+ language?: string;
232
213
 
233
- **Example:**
234
- ```typescript
235
- const finalResult = await session.finalize();
236
- console.log(`Final result: ${finalResult.segments.length} segments`);
237
- ```
214
+ /** Translate non-English speech to English (default: false) */
215
+ translate?: boolean;
238
216
 
239
- #### `close(): void`
217
+ /** Auto-detect spoken language. Overrides 'language' when true. (default: false) */
218
+ detectLanguage?: boolean;
240
219
 
241
- Releases all native resources associated with the streaming session. This method is idempotent and safe to call multiple times.
220
+ // === Sampling ===
221
+ /** Sampling temperature. 0.0 = greedy deterministic. (default: 0.0) */
222
+ temperature?: number;
242
223
 
243
- **Example:**
244
- ```typescript
245
- session.close();
246
- ```
224
+ /** Temperature increment for fallback retries (default: 0.2) */
225
+ temperatureInc?: number;
247
226
 
248
- #### `get isClosed: boolean`
227
+ /** Disable temperature fallback. If true, temperatureInc is ignored. (default: false) */
228
+ noFallback?: boolean;
249
229
 
250
- Indicates whether the session has been closed.
230
+ /** Beam search size. -1 uses greedy decoding. >1 enables beam search. (default: -1) */
231
+ beamSize?: number;
251
232
 
252
- **Returns:** `boolean` `true` if the session is closed, `false` otherwise
233
+ /** Best-of-N sampling candidates for greedy decoding (default: 5) */
234
+ bestOf?: number;
253
235
 
254
- ### Types
236
+ // === Thresholds ===
237
+ /** Entropy threshold for decoder fallback (default: 2.4) */
238
+ entropyThold?: number;
255
239
 
256
- #### `ModelConfig`
240
+ /** Log probability threshold for decoder fallback (default: -1.0) */
241
+ logprobThold?: number;
257
242
 
258
- Configuration object for loading diarization models.
243
+ /** No-speech probability threshold (default: 0.6) */
244
+ noSpeechThold?: number;
259
245
 
260
- ```typescript
261
- interface ModelConfig {
262
- segModelPath: string; // Path to segmentation GGUF model file
263
- embModelPath: string; // Path to embedding GGUF model file
264
- pldaPath: string; // Path to PLDA GGUF model file
265
- coremlPath: string; // Path to embedding CoreML .mlpackage directory
266
- segCoremlPath: string; // Path to segmentation CoreML .mlpackage directory
267
- }
268
- ```
246
+ // === Context ===
247
+ /** Initial prompt text to condition the decoder (default: none) */
248
+ prompt?: string;
269
249
 
270
- #### `VADChunk`
250
+ /** Don't use previous segment as context for next segment (default: true) */
251
+ noContext?: boolean;
271
252
 
272
- Voice activity detection result for a single 10-second audio chunk.
253
+ /** Suppress blank outputs at the beginning of segments (default: true) */
254
+ suppressBlank?: boolean;
273
255
 
274
- ```typescript
275
- interface VADChunk {
276
- chunkIndex: number; // Zero-based chunk number (increments every 1 second)
277
- startTime: number; // Absolute start time in seconds (chunkIndex * 1.0)
278
- duration: number; // Always 10.0 (chunk window size)
279
- numFrames: number; // Always 589 (segmentation model output frames)
280
- vad: Float32Array; // [589] frame-level voice activity: 1.0 if any speaker active, 0.0 otherwise
256
+ /** Suppress non-speech tokens (default: false) */
257
+ suppressNst?: boolean;
281
258
  }
282
- ```
283
259
 
284
- The `vad` array contains 589 frames, each representing approximately 17ms of audio. A value of 1.0 indicates speech activity (any speaker), 0.0 indicates silence.
260
+ export interface AlignedSegment {
261
+ /** Global speaker label (e.g., SPEAKER_00). */
262
+ speaker: string;
285
263
 
286
- #### `Segment`
264
+ /** Segment start time in seconds. */
265
+ start: number;
287
266
 
288
- A contiguous speech segment with speaker label.
267
+ /** Segment duration in seconds. */
268
+ duration: number;
289
269
 
290
- ```typescript
291
- interface Segment {
292
- start: number; // Start time in seconds
293
- duration: number; // Duration in seconds
294
- speaker: string; // Speaker label (e.g., "SPEAKER_00", "SPEAKER_01", ...)
270
+ /** Transcribed text for this segment. */
271
+ text: string;
295
272
  }
296
- ```
297
-
298
- #### `DiarizationResult`
299
-
300
- Complete diarization output with speaker-labeled segments.
301
273
 
302
- ```typescript
303
- interface DiarizationResult {
304
- segments: Segment[]; // Array of segments, sorted by start time
274
+ export interface TranscriptionResult {
275
+ /** Full speaker-labeled transcript segments. */
276
+ segments: AlignedSegment[];
305
277
  }
306
278
  ```
307
279
 
308
280
  ## Usage Examples
309
281
 
310
- ### Example 1: Offline Diarization
311
-
312
- Process an entire audio file and print a timeline of speaker segments.
282
+ ### One-shot transcription
313
283
 
314
284
  ```typescript
315
- import { Pyannote } from 'pyannote-cpp-node';
316
- import { readFileSync } from 'node:fs';
317
-
318
- // Helper to load 16-bit PCM WAV and convert to Float32Array
319
- function loadWavFile(filePath: string): Float32Array {
320
- const buffer = readFileSync(filePath);
321
- const view = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
322
-
323
- // Find data chunk
324
- let offset = 12; // Skip RIFF header
325
- while (offset < view.byteLength - 8) {
326
- const chunkId = String.fromCharCode(
327
- view.getUint8(offset),
328
- view.getUint8(offset + 1),
329
- view.getUint8(offset + 2),
330
- view.getUint8(offset + 3)
331
- );
332
- const chunkSize = view.getUint32(offset + 4, true);
333
- offset += 8;
334
-
335
- if (chunkId === 'data') {
336
- // Convert Int16 PCM to Float32 by dividing by 32768
337
- const numSamples = chunkSize / 2;
338
- const float32 = new Float32Array(numSamples);
339
- for (let i = 0; i < numSamples; i++) {
340
- float32[i] = view.getInt16(offset + i * 2, true) / 32768.0;
341
- }
342
- return float32;
343
- }
285
+ import { Pipeline } from 'pyannote-cpp-node';
344
286
 
345
- offset += chunkSize;
346
- if (chunkSize % 2 !== 0) offset++; // Align to word boundary
347
- }
348
-
349
- throw new Error('No data chunk found in WAV file');
350
- }
351
-
352
- async function main() {
353
- // Load model
354
- const model = await Pyannote.load({
287
+ async function runOneShot(audio: Float32Array) {
288
+ const pipeline = await Pipeline.load({
355
289
  segModelPath: './models/segmentation.gguf',
356
290
  embModelPath: './models/embedding.gguf',
357
291
  pldaPath: './models/plda.gguf',
358
292
  coremlPath: './models/embedding.mlpackage',
359
293
  segCoremlPath: './models/segmentation.mlpackage',
294
+ whisperModelPath: './models/ggml-large-v3-turbo-q5_0.bin',
360
295
  });
361
296
 
362
- // Load audio
363
- const audio = loadWavFile('./audio.wav');
364
- console.log(`Loaded ${audio.length} samples (${(audio.length / 16000).toFixed(1)}s)`);
365
-
366
- // Diarize
367
- const result = await model.diarize(audio);
297
+ const result = await pipeline.transcribe(audio);
368
298
 
369
- // Print timeline
370
- console.log(`\nDetected ${result.segments.length} segments:`);
371
- for (const segment of result.segments) {
372
- const startTime = segment.start.toFixed(2);
373
- const endTime = (segment.start + segment.duration).toFixed(2);
374
- console.log(`[${startTime}s - ${endTime}s] ${segment.speaker}`);
299
+ for (const seg of result.segments) {
300
+ const end = seg.start + seg.duration;
301
+ console.log(`[${seg.speaker}] ${seg.start.toFixed(2)}-${end.toFixed(2)} ${seg.text.trim()}`);
375
302
  }
376
303
 
377
- // Count speakers
378
- const speakers = new Set(result.segments.map(s => s.speaker));
379
- console.log(`\nTotal speakers: ${speakers.size}`);
380
-
381
- model.close();
304
+ pipeline.close();
382
305
  }
383
-
384
- main();
385
306
  ```
386
307
 
387
- ### Example 2: Streaming Diarization
388
-
389
- Process audio incrementally in 1-second chunks, displaying real-time VAD.
308
+ ### Streaming transcription
390
309
 
391
310
  ```typescript
392
- import { Pyannote } from 'pyannote-cpp-node';
311
+ import { Pipeline } from 'pyannote-cpp-node';
393
312
 
394
- async function streamingDiarization() {
395
- const model = await Pyannote.load({
313
+ async function runStreaming(audio: Float32Array) {
314
+ const pipeline = await Pipeline.load({
396
315
  segModelPath: './models/segmentation.gguf',
397
316
  embModelPath: './models/embedding.gguf',
398
317
  pldaPath: './models/plda.gguf',
399
318
  coremlPath: './models/embedding.mlpackage',
400
319
  segCoremlPath: './models/segmentation.mlpackage',
320
+ whisperModelPath: './models/ggml-large-v3-turbo-q5_0.bin',
401
321
  });
402
322
 
403
- const session = model.createStreamingSession();
404
-
405
- // Load full audio file
406
- const audio = loadWavFile('./audio.wav');
407
-
408
- // Push audio in 1-second chunks (16,000 samples)
409
- const CHUNK_SIZE = 16000;
410
- let totalChunks = 0;
411
-
412
- for (let offset = 0; offset < audio.length; offset += CHUNK_SIZE) {
413
- const end = Math.min(offset + CHUNK_SIZE, audio.length);
414
- const chunk = audio.slice(offset, end);
415
-
416
- const vadChunks = await session.push(chunk);
417
-
418
- // VAD chunks are returned after first 10 seconds
419
- for (const vad of vadChunks) {
420
- // Count active frames (speech detected)
421
- const activeFrames = vad.vad.filter(v => v > 0.5).length;
422
- const speechRatio = (activeFrames / vad.numFrames * 100).toFixed(1);
423
-
424
- console.log(
425
- `Chunk ${vad.chunkIndex}: ${vad.startTime.toFixed(1)}s - ${(vad.startTime + vad.duration).toFixed(1)}s | ` +
426
- `Speech: ${speechRatio}%`
427
- );
428
- totalChunks++;
323
+ const session = pipeline.createSession();
324
+ session.on('segments', (segments) => {
325
+ const latest = segments[segments.length - 1];
326
+ if (latest) {
327
+ const end = latest.start + latest.duration;
328
+ console.log(`[live][${latest.speaker}] ${latest.start.toFixed(2)}-${end.toFixed(2)} ${latest.text.trim()}`);
429
329
  }
430
- }
431
-
432
- console.log(`\nProcessed ${totalChunks} chunks`);
433
-
434
- // Get final diarization result
435
- console.log('\nFinalizing...');
436
- const result = await session.finalize();
437
-
438
- console.log(`\nFinal result: ${result.segments.length} segments`);
439
- for (const segment of result.segments) {
440
- console.log(
441
- `[${segment.start.toFixed(2)}s - ${(segment.start + segment.duration).toFixed(2)}s] ${segment.speaker}`
442
- );
443
- }
444
-
445
- session.close();
446
- model.close();
447
- }
448
-
449
- streamingDiarization();
450
- ```
451
-
452
- ### Example 3: On-Demand Reclustering
453
-
454
- Push audio and trigger reclustering every 30 seconds to get intermediate results.
455
-
456
- ```typescript
457
- import { Pyannote } from 'pyannote-cpp-node';
458
-
459
- async function reclusteringExample() {
460
- const model = await Pyannote.load({
461
- segModelPath: './models/segmentation.gguf',
462
- embModelPath: './models/embedding.gguf',
463
- pldaPath: './models/plda.gguf',
464
- coremlPath: './models/embedding.mlpackage',
465
- segCoremlPath: './models/segmentation.mlpackage',
466
330
  });
467
331
 
468
- const session = model.createStreamingSession();
469
- const audio = loadWavFile('./audio.wav');
470
-
471
- const CHUNK_SIZE = 16000; // 1 second
472
- const RECLUSTER_INTERVAL = 30; // Recluster every 30 seconds
473
-
474
- let secondsProcessed = 0;
475
-
476
- for (let offset = 0; offset < audio.length; offset += CHUNK_SIZE) {
477
- const end = Math.min(offset + CHUNK_SIZE, audio.length);
478
- const chunk = audio.slice(offset, end);
479
-
480
- await session.push(chunk);
481
- secondsProcessed++;
482
-
483
- // Recluster every 30 seconds
484
- if (secondsProcessed % RECLUSTER_INTERVAL === 0) {
485
- console.log(`\n--- Reclustering at ${secondsProcessed}s ---`);
486
- const intermediateResult = await session.recluster();
487
-
488
- const speakers = new Set(intermediateResult.segments.map(s => s.speaker));
489
- console.log(`Current speakers detected: ${speakers.size}`);
490
- console.log(`Current segments: ${intermediateResult.segments.length}`);
332
+ const chunkSize = 16000;
333
+ for (let i = 0; i < audio.length; i += chunkSize) {
334
+ const chunk = audio.slice(i, Math.min(i + chunkSize, audio.length));
335
+ const vad = await session.push(chunk);
336
+ if (vad.length > 0) {
337
+ const speechFrames = vad.filter(Boolean).length;
338
+ console.log(`VAD frames: ${vad.length}, speech frames: ${speechFrames}`);
491
339
  }
492
340
  }
493
341
 
494
- // Final result
495
- console.log('\n--- Final result ---');
496
342
  const finalResult = await session.finalize();
497
- const speakers = new Set(finalResult.segments.map(s => s.speaker));
498
- console.log(`Total speakers: ${speakers.size}`);
499
- console.log(`Total segments: ${finalResult.segments.length}`);
343
+ console.log(`Final segments: ${finalResult.segments.length}`);
500
344
 
501
345
  session.close();
502
- model.close();
346
+ pipeline.close();
503
347
  }
504
-
505
- reclusteringExample();
506
348
  ```
507
349
 
508
- ### Example 4: Generating RTTM Output
509
-
510
- Format diarization results into standard RTTM (Rich Transcription Time Marked) format.
350
+ ### Custom Whisper decode options
511
351
 
512
352
  ```typescript
513
- import { Pyannote, type DiarizationResult } from 'pyannote-cpp-node';
514
- import { writeFileSync } from 'node:fs';
515
-
516
- function toRTTM(result: DiarizationResult, filename: string = 'audio'): string {
517
- const lines = result.segments.map(segment => {
518
- // RTTM format: SPEAKER <file> <chnl> <tbeg> <tdur> <ortho> <stype> <name> <conf> <slat>
519
- return [
520
- 'SPEAKER',
521
- filename,
522
- '1',
523
- segment.start.toFixed(3),
524
- segment.duration.toFixed(3),
525
- '<NA>',
526
- '<NA>',
527
- segment.speaker,
528
- '<NA>',
529
- '<NA>',
530
- ].join(' ');
531
- });
532
-
533
- return lines.join('\n') + '\n';
534
- }
353
+ import { Pipeline } from 'pyannote-cpp-node';
535
354
 
536
- async function generateRTTM() {
537
- const model = await Pyannote.load({
538
- segModelPath: './models/segmentation.gguf',
539
- embModelPath: './models/embedding.gguf',
540
- pldaPath: './models/plda.gguf',
541
- coremlPath: './models/embedding.mlpackage',
542
- segCoremlPath: './models/segmentation.mlpackage',
543
- });
544
-
545
- const audio = loadWavFile('./audio.wav');
546
- const result = await model.diarize(audio);
355
+ const pipeline = await Pipeline.load({
356
+ segModelPath: './models/segmentation.gguf',
357
+ embModelPath: './models/embedding.gguf',
358
+ pldaPath: './models/plda.gguf',
359
+ coremlPath: './models/embedding.mlpackage',
360
+ segCoremlPath: './models/segmentation.mlpackage',
361
+ whisperModelPath: './models/ggml-large-v3-turbo-q5_0.bin',
362
+
363
+ // Whisper runtime options
364
+ useGpu: true,
365
+ flashAttn: true,
366
+ gpuDevice: 0,
367
+ useCoreml: false,
368
+
369
+ // Decode strategy
370
+ nThreads: 8,
371
+ language: 'ko',
372
+ translate: false,
373
+ detectLanguage: false,
374
+ temperature: 0.0,
375
+ temperatureInc: 0.2,
376
+ noFallback: false,
377
+ beamSize: 5,
378
+ bestOf: 5,
379
+
380
+ // Thresholds and context
381
+ entropyThold: 2.4,
382
+ logprobThold: -1.0,
383
+ noSpeechThold: 0.6,
384
+ prompt: 'Meeting transcript with technical terminology.',
385
+ noContext: true,
386
+ suppressBlank: true,
387
+ suppressNst: false,
388
+ });
389
+ ```
547
390
 
548
- // Generate RTTM
549
- const rttm = toRTTM(result, 'audio');
550
-
551
- // Write to file
552
- writeFileSync('./output.rttm', rttm);
553
- console.log('RTTM file written to output.rttm');
391
+ ## JSON Output Format
554
392
 
555
- // Also print to console
556
- console.log('\nRTTM output:');
557
- console.log(rttm);
393
+ The pipeline returns this JSON shape:
558
394
 
559
- model.close();
395
+ ```json
396
+ {
397
+ "segments": [
398
+ {
399
+ "speaker": "SPEAKER_00",
400
+ "start": 0.497000,
401
+ "duration": 2.085000,
402
+ "text": "Hello world"
403
+ }
404
+ ]
560
405
  }
561
-
562
- generateRTTM();
563
406
  ```
564
407
 
565
- ## Architecture
566
-
567
- The diarization pipeline consists of four main stages:
568
-
569
- ### 1. Segmentation (SincNet + BiLSTM)
570
-
571
- The segmentation model processes 10-second audio windows and outputs 7-class powerset logits for 589 frames (approximately one frame every 17ms). The model architecture:
572
-
573
- - **SincNet**: Learnable sinc filter bank for feature extraction
574
- - **4-layer BiLSTM**: Bidirectional long short-term memory layers
575
- - **Linear classifier**: Projects to 7 powerset classes with log-softmax
576
-
577
- The 7 powerset classes represent all possible combinations of up to 3 simultaneous speakers:
578
- - Class 0: silence (no speakers)
579
- - Classes 1-3: single speakers
580
- - Classes 4-6: speaker overlaps
581
-
582
- ### 2. Powerset Decoding
583
-
584
- Converts the 7-class powerset predictions into binary speaker activity for 3 local speakers per chunk. Each frame is decoded to indicate which of the 3 local speaker "slots" are active.
585
-
586
- ### 3. Embedding Extraction (WeSpeaker ResNet34)
587
-
588
- For each active speaker in each chunk, the embedding model extracts a 256-dimensional speaker vector:
589
-
590
- - **Mel filterbank**: 80-bin log-mel spectrogram features
591
- - **ResNet34**: Deep residual network for speaker representation
592
- - **Output**: 256-dimensional L2-normalized embedding
593
-
594
- Silent speakers receive NaN embeddings, which are filtered before clustering.
595
-
596
- ### 4. Clustering (PLDA + AHC + VBx)
597
-
598
- The final stage maps local speaker labels to global speaker identities:
599
-
600
- - **PLDA transformation**: Probabilistic Linear Discriminant Analysis projects embeddings from 256 to 128 dimensions
601
- - **Agglomerative Hierarchical Clustering (AHC)**: fastcluster implementation with O(n²) complexity, using centroid linkage and a distance threshold of 0.6
602
- - **VBx refinement**: Variational Bayes diarization with parameters FA=0.07, FB=0.8, maximum 20 iterations
603
-
604
- The clustering stage computes speaker centroids and assigns each embedding to the closest centroid while respecting the constraint that two local speakers in the same chunk cannot map to the same global speaker.
605
-
606
- ### CoreML Acceleration
607
-
608
- Both neural networks run on Apple's CoreML framework, which automatically distributes computation across:
609
-
610
- - **Neural Engine**: Dedicated ML accelerator on Apple Silicon
611
- - **GPU**: Metal-accelerated operations
612
- - **CPU**: Fallback for unsupported operations
613
-
614
- CoreML models use Float16 computation for optimal performance while maintaining accuracy within acceptable bounds (cosine similarity > 0.999 vs Float32).
615
-
616
- ### Streaming Architecture
617
-
618
- The streaming API uses a sliding 10-second window with a 1-second hop (9 seconds of overlap between consecutive chunks). Three data stores maintain the state:
619
-
620
- - **`audio_buffer`**: Sliding window (~10s, ~640 KB for 1 hour) — old samples are discarded
621
- - **`embeddings`**: Grows forever (~11 MB for 1 hour) — stores 3 × 256-dim vectors per chunk (NaN for silent speakers)
622
- - **`binarized`**: Grows forever (~25 MB for 1 hour) — stores 589 × 3 binary activity masks per chunk
623
-
624
- During reclustering, all accumulated embeddings are used to compute soft cluster assignments, and all binarized segmentations are used to reconstruct the global timeline. This is why the `embeddings` and `binarized` arrays must persist for the entire session.
625
-
626
- ### Constants
627
-
628
- | Constant | Value | Description |
629
- |----------|-------|-------------|
630
- | SAMPLE_RATE | 16000 Hz | Audio sample rate |
631
- | CHUNK_SAMPLES | 160000 | 10-second window size |
632
- | STEP_SAMPLES | 16000 | 1-second hop between chunks |
633
- | FRAMES_PER_CHUNK | 589 | Segmentation output frames |
634
- | NUM_LOCAL_SPEAKERS | 3 | Maximum speakers per chunk |
635
- | EMBEDDING_DIM | 256 | Speaker embedding dimension |
636
- | FBANK_NUM_BINS | 80 | Mel filterbank bins |
637
-
638
408
  ## Audio Format Requirements
639
409
 
640
- The library expects raw PCM audio in a specific format:
641
-
642
- - **Sample rate**: 16000 Hz (16 kHz) — **required**
643
- - **Channels**: Mono (single channel) — **required**
644
- - **Format**: `Float32Array` with values in the range **[-1.0, 1.0]**
645
-
646
- The library does **not** handle audio decoding. You must provide raw PCM samples.
647
-
648
- ### Loading Audio Files
649
-
650
- For WAV files, you can use the `loadWavFile` function from Example 1, or use third-party libraries:
651
-
652
- ```bash
653
- npm install node-wav
654
- ```
655
-
656
- ```typescript
657
- import { read } from 'node-wav';
658
- import { readFileSync } from 'node:fs';
659
-
660
- const buffer = readFileSync('./audio.wav');
661
- const wav = read(buffer);
662
-
663
- // Convert to mono if stereo
664
- const mono = wav.channelData.length > 1
665
- ? wav.channelData[0].map((v, i) => (v + wav.channelData[1][i]) / 2)
666
- : wav.channelData[0];
667
-
668
- // Resample to 16kHz if needed (using a resampling library)
669
- // ...
670
-
671
- const audio = new Float32Array(mono);
672
- ```
673
-
674
- For other audio formats (MP3, M4A, etc.), use ffmpeg to convert to 16kHz mono WAV first:
675
-
676
- ```bash
677
- ffmpeg -i input.mp3 -ar 16000 -ac 1 -f f32le -acodec pcm_f32le - | \
678
- node process.js
679
- ```
410
+ - Input must be `Float32Array`
411
+ - Sample rate must be `16000` Hz
412
+ - Audio must be mono
413
+ - Recommended amplitude range: `[-1.0, 1.0]`
680
414
 
681
- ## Important Notes and Caveats
415
+ All API methods expect decoded PCM samples; file decoding/resampling is handled by the caller.
682
416
 
683
- ### Platform Limitations
684
-
685
- - **macOS only**: The library requires CoreML for neural network inference. There is currently no fallback implementation for other platforms.
686
- - **No Linux/Windows support**: CoreML is exclusive to Apple platforms.
687
-
688
- ### `recluster()` Mutates State
689
-
690
- The `recluster()` method overwrites the internal session state, specifically replacing the `embeddings` and chunk index arrays with filtered versions (excluding NaN embeddings from silent speakers). This means:
691
-
692
- - Calling `push()` after `recluster()` may produce incorrect results
693
- - Subsequent `recluster()` calls may not work as expected
694
- - The data structure assumes the original unfiltered layout (3 embeddings per chunk)
695
-
696
- **Best practice**: Use `recluster()` sparingly for live progress updates (e.g., every 30 seconds), or avoid it entirely and only call `finalize()` when the stream ends.
697
-
698
- ### Operations Are Serialized
699
-
700
- Operations on a streaming session are serialized internally. Do not call `push()` while another `push()`, `recluster()`, or `finalize()` is in progress. Wait for the Promise to resolve before making the next call.
701
-
702
- ### Resource Management
703
-
704
- - **Close sessions before models**: Always close streaming sessions before closing the parent model
705
- - **Idempotent close**: Both `model.close()` and `session.close()` are safe to call multiple times
706
- - **No reuse after close**: Once closed, models and sessions cannot be reused
707
-
708
- ### Model Loading
709
-
710
- - **Path validation**: `Pyannote.load()` validates that all paths exist using `fs.accessSync()` before initialization
711
- - **CoreML compilation**: The CoreML framework compiles `.mlpackage` models internally on first load (typically fast, ~100ms)
712
- - **No explicit loading step**: Model weights are loaded synchronously in the constructor
713
-
714
- ### Threading Model
715
-
716
- All heavy operations (`diarize`, `push`, `recluster`, `finalize`) run on libuv worker threads and never block the Node.js event loop. However, the operations do hold native locks internally, so concurrent operations on the same session are serialized.
717
-
718
- ### Memory Usage
417
+ ## Architecture
719
418
 
720
- For a 1-hour audio file:
721
- - `audio_buffer`: ~640 KB (sliding window)
722
- - `embeddings`: ~11 MB (grows throughout session)
723
- - `binarized`: ~25 MB (grows throughout session)
724
- - CoreML models: ~50 MB (loaded once per model)
419
+ The integrated pipeline runs in 7 stages:
725
420
 
726
- Total memory footprint: approximately 100 MB for a 1-hour streaming session.
421
+ 1. VAD silence filter (optional compression of long silence)
422
+ 2. Audio buffer (stream-safe FIFO with timestamp tracking)
423
+ 3. Segmentation (speech activity over rolling windows)
424
+ 4. Transcription (Whisper sentence-level segments)
425
+ 5. Alignment (segment-level speaker assignment by overlap)
426
+ 6. Finalize (flush + final recluster + final alignment)
427
+ 7. Callback/event emission (`segments` updates)
727
428
 
728
429
  ## Performance
729
430
 
730
- Measured on Apple M2 Pro with 16 GB RAM:
731
-
732
- | Component | Time per Chunk | Notes |
733
- |-----------|----------------|-------|
734
- | Segmentation (CoreML) | ~12ms | 10-second audio window, 589 frames |
735
- | Embedding (CoreML) | ~13ms | Per speaker per chunk (up to 3 speakers) |
736
- | AHC Clustering | ~0.8s | 3000 embeddings (1000 chunks) |
737
- | VBx Refinement | ~1.2s | 20 iterations, 3000 embeddings |
738
- | **Full Pipeline (offline)** | **39x real-time** | 45-minute audio processed in 70 seconds |
739
-
740
- ### Streaming Performance
431
+ - Diarization only: **39x real-time**
432
+ - Integrated transcription + diarization: **~14.6x real-time**
433
+ - 45-minute Korean meeting test (6 speakers): **2713s audio in 186s**
434
+ - Each Whisper segment maps 1:1 to a speaker-labeled segment (no merging)
435
+ - Speaker confusion rate: **2.55%**
741
436
 
742
- - **First chunk latency**: 10 seconds (requires full window)
743
- - **Incremental latency**: ~30ms per 1-second push (after first chunk)
744
- - **Recluster latency**: ~2 seconds for 30 minutes of audio (~1800 embeddings)
437
+ ## Platform Support
745
438
 
746
- Streaming mode has higher per-chunk overhead due to the incremental nature but enables real-time applications.
747
-
748
- ## Supported Platforms
749
-
750
- | Platform | Architecture | Status |
751
- |----------|--------------|--------|
752
- | macOS | arm64 (Apple Silicon) | ✅ Supported |
753
- | macOS | x64 (Intel) | 🔜 Planned |
754
- | Linux | any | ❌ Not supported (CoreML unavailable) |
755
- | Windows | any | ❌ Not supported (CoreML unavailable) |
756
-
757
- Intel macOS support is planned but not yet available. The CoreML dependency makes cross-platform support challenging without alternative inference backends.
439
+ | Platform | Status |
440
+ | --- | --- |
441
+ | macOS arm64 (Apple Silicon) | Supported |
442
+ | macOS x64 (Intel) | Supported |
443
+ | Linux | Not supported |
444
+ | Windows | Not supported |
758
445
 
759
446
  ## License
760
447
 
761
448
  MIT
762
-
763
- ---
764
-
765
- For issues, feature requests, or contributions, please visit the [GitHub repository](https://github.com/predict-woo/pyannote-ggml).