@clipkit/speech-to-text 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Clipkit Contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,57 @@
1
+ # @clipkit/speech-to-text
2
+
3
+ Transcribe an audio/video source into **word-timestamped captions** for Clipkit.
4
+
5
+ One Whisper model (via [Transformers.js](https://github.com/huggingface/transformers.js) / ONNX) runs the **same** in the browser (WebGPU/WASM) and in Node (`onnxruntime-node`) — no paid API, no native binaries, MIT-licensed weights. The output maps straight onto the protocol's `caption` element `words[]`.
6
+
7
+ **Authoring-time only.** The runtime never sees this package — it just renders the `words[]` we produce. The protocol is unchanged; this is the layer that *fills* a caption.
8
+
9
+ ## Pipeline
10
+
11
+ ```
12
+ audio/video file ──decode──▶ 16 kHz mono PCM ──transcribe──▶ TranscriptResult ──toCaptionWords──▶ caption.words[]
13
+ (env-specific) (Whisper/ONNX) (the protocol bridge)
14
+ ```
15
+
16
+ - **`transcribe(audio, opts?)`** — 16 kHz mono PCM → word-timestamped transcript. Env-agnostic.
17
+ - **`toCaptionWords(result, opts?)`** — transcript → `caption` element `words[]`. Pure; the one place this meets the protocol.
18
+ - **Audio decode is env-specific** — import from the matching entry point.
19
+
20
+ ## Node
21
+
22
+ ```ts
23
+ import { transcribe, toCaptionWords } from '@clipkit/speech-to-text';
24
+ import { decodeAudioFile } from '@clipkit/speech-to-text/node'; // needs ffmpeg on PATH
25
+
26
+ const audio = await decodeAudioFile('clip.mp4');
27
+ const result = await transcribe(audio, { model: 'Xenova/whisper-base' });
28
+ const words = toCaptionWords(result);
29
+ // → a caption element: { type: 'caption', time: 0, track: 3, words }
30
+ ```
31
+
32
+ ## Browser
33
+
34
+ ```ts
35
+ import { transcribe, toCaptionWords } from '@clipkit/speech-to-text';
36
+ import { decodeAudioBlob } from '@clipkit/speech-to-text/browser'; // WebAudio
37
+
38
+ const audio = await decodeAudioBlob(file); // a File/Blob
39
+ const result = await transcribe(audio); // WebGPU when available
40
+ ```
41
+
42
+ ## Models
43
+
44
+ `model` is any Whisper variant on the Hugging Face hub; default `Xenova/whisper-base`. Trade size/speed for accuracy: `whisper-tiny(.en)` (~40 MB, fast) → `whisper-base` → `whisper-small` (~250 MB). `.en` variants are English-only and faster. The model downloads once and is cached (browser cache / Node fs).
45
+
46
+ ## Notes
47
+
48
+ - **Word timestamps** use Whisper's `return_timestamps: 'word'`. Quality scales with model size; for tight sync, prefer `base`/`small`.
49
+ - **`offset`** on `toCaptionWords` shifts absolute audio times to be relative to the caption element's `time` (the protocol stores word times relative to the element).
50
+ - On Node, `onnxruntime-node` may print a harmless `mutex lock failed` line during process **teardown** (after results are produced) — an upstream thread-pool cleanup quirk, not a transcription error.
51
+
52
+ ## Verify
53
+
54
+ ```
55
+ npm run build && node --test test/caption.test.mjs # protocol bridge (fast, no model)
56
+ node test/smoke.mjs [file] # end-to-end (downloads a model)
57
+ ```
@@ -0,0 +1,9 @@
1
+ import type { MonoAudio } from './types.js';
2
+ /**
3
+ * Decode audio bytes (any format the browser supports — mp4/mov/mp3/wav/webm)
4
+ * to 16 kHz mono float PCM. Pass a File/Blob's ArrayBuffer.
5
+ */
6
+ export declare function decodeAudioData(data: ArrayBuffer): Promise<MonoAudio>;
7
+ /** Convenience: decode a File/Blob directly. */
8
+ export declare function decodeAudioBlob(blob: Blob): Promise<MonoAudio>;
9
+ //# sourceMappingURL=audio.browser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audio.browser.d.ts","sourceRoot":"","sources":["../src/audio.browser.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAI5C;;;GAGG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,WAAW,GAAG,OAAO,CAAC,SAAS,CAAC,CAa3E;AAED,gDAAgD;AAChD,wBAAsB,eAAe,CAAC,IAAI,EAAE,IAAI,GAAG,OAAO,CAAC,SAAS,CAAC,CAEpE"}
@@ -0,0 +1,29 @@
1
+ // Browser audio extraction — a File/Blob/ArrayBuffer (audio or video) → 16 kHz
2
+ // mono PCM, via WebAudio's OfflineAudioContext (decode + resample in one pass).
3
+ // The only browser-specific piece; the engine itself is env-agnostic.
4
+ //
5
+ // Import path: `@clipkit/speech-to-text/browser`.
6
+ const SAMPLE_RATE = 16000;
7
+ /**
8
+ * Decode audio bytes (any format the browser supports — mp4/mov/mp3/wav/webm)
9
+ * to 16 kHz mono float PCM. Pass a File/Blob's ArrayBuffer.
10
+ */
11
+ export async function decodeAudioData(data) {
12
+ // Decode at native rate first (decodeAudioData needs a real context), then
13
+ // resample to 16 kHz mono with an OfflineAudioContext render pass.
14
+ const tmp = new OfflineAudioContext(1, 1, 44100);
15
+ const decoded = await tmp.decodeAudioData(data.slice(0));
16
+ const frames = Math.ceil(decoded.duration * SAMPLE_RATE);
17
+ const offline = new OfflineAudioContext(1, Math.max(1, frames), SAMPLE_RATE);
18
+ const src = offline.createBufferSource();
19
+ src.buffer = decoded;
20
+ src.connect(offline.destination);
21
+ src.start();
22
+ const rendered = await offline.startRendering();
23
+ return { samples: rendered.getChannelData(0).slice(), sampleRate: SAMPLE_RATE };
24
+ }
25
+ /** Convenience: decode a File/Blob directly. */
26
+ export async function decodeAudioBlob(blob) {
27
+ return decodeAudioData(await blob.arrayBuffer());
28
+ }
29
+ //# sourceMappingURL=audio.browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audio.browser.js","sourceRoot":"","sources":["../src/audio.browser.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,gFAAgF;AAChF,sEAAsE;AACtE,EAAE;AACF,kDAAkD;AAIlD,MAAM,WAAW,GAAG,KAAK,CAAC;AAE1B;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,IAAiB;IACrD,2EAA2E;IAC3E,mEAAmE;IACnE,MAAM,GAAG,GAAG,IAAI,mBAAmB,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC;IACjD,MAAM,OAAO,GAAG,MAAM,GAAG,CAAC,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;IACzD,MAAM,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,GAAG,WAAW,CAAC,CAAC;IACzD,MAAM,OAAO,GAAG,IAAI,mBAAmB,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,WAAW,CAAC,CAAC;IAC7E,MAAM,GAAG,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC;IACzC,GAAG,CAAC,MAAM,GAAG,OAAO,CAAC;IACrB,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;IACjC,GAAG,CAAC,KAAK,EAAE,CAAC;IACZ,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,cAAc,EAAE,CAAC;IAChD,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,cAAc,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,CAAC;AAClF,CAAC;AAED,gDAAgD;AAChD,MAAM,CAAC,KAAK,UAAU,eAAe,CAAC,IAAU;IAC9C,OAAO,eAAe,CAAC,MAAM,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC;AACnD,CAAC"}
@@ -0,0 +1,7 @@
1
+ import type { MonoAudio } from './types.js';
2
+ /**
3
+ * Decode an audio/video file to 16 kHz mono float PCM. Requires `ffmpeg` on PATH.
4
+ * Works for any container ffmpeg reads (mp4, mov, mp3, wav, m4a, webm, …).
5
+ */
6
+ export declare function decodeAudioFile(path: string): Promise<MonoAudio>;
7
+ //# sourceMappingURL=audio.node.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audio.node.d.ts","sourceRoot":"","sources":["../src/audio.node.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAI5C;;;GAGG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAsBtE"}
@@ -0,0 +1,36 @@
1
+ // Node audio extraction — any audio/video file → 16 kHz mono PCM, via the
2
+ // system `ffmpeg` (already a Clipkit toolchain dependency). This is the only
3
+ // Node-specific piece; the transcription engine itself is env-agnostic.
4
+ //
5
+ // Import path: `@clipkit/speech-to-text/node`.
6
+ import { spawn } from 'node:child_process';
7
+ const SAMPLE_RATE = 16000;
8
+ /**
9
+ * Decode an audio/video file to 16 kHz mono float PCM. Requires `ffmpeg` on PATH.
10
+ * Works for any container ffmpeg reads (mp4, mov, mp3, wav, m4a, webm, …).
11
+ */
12
+ export async function decodeAudioFile(path) {
13
+ // -f f32le: raw 32-bit float little-endian; -ac 1: mono; -ar 16000: 16 kHz.
14
+ const args = ['-i', path, '-f', 'f32le', '-ac', '1', '-ar', String(SAMPLE_RATE), '-hide_banner', '-loglevel', 'error', 'pipe:1'];
15
+ const chunks = [];
16
+ const errChunks = [];
17
+ await new Promise((resolve, reject) => {
18
+ const ff = spawn('ffmpeg', args);
19
+ ff.stdout.on('data', (d) => chunks.push(d));
20
+ ff.stderr.on('data', (d) => errChunks.push(d));
21
+ ff.on('error', (e) => reject(new Error(`ffmpeg failed to start (is it installed?): ${e.message}`)));
22
+ ff.on('close', (code) => {
23
+ if (code === 0)
24
+ resolve();
25
+ else
26
+ reject(new Error(`ffmpeg exited ${code}: ${Buffer.concat(errChunks).toString().trim()}`));
27
+ });
28
+ });
29
+ const buf = Buffer.concat(chunks);
30
+ // Float32 view over the raw bytes (copy into an aligned ArrayBuffer).
31
+ const samples = new Float32Array(buf.byteLength / 4);
32
+ for (let i = 0; i < samples.length; i++)
33
+ samples[i] = buf.readFloatLE(i * 4);
34
+ return { samples, sampleRate: S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AC,OAAO,EAAE,CAAC,IAAI,EAAE,EAAE;YACtB,IAAI,IAAI,KAAK,CAAC;gBAAE,OAAO,EAAE,CAAC;;gBACrB,MAAM,CAAC,IAAI,KAAK,CAAC,iBAAiB,IAAI,KAAK,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CAAC;QACjG,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAClC,sEAAsE;IACtE,MAAM,OAAO,GAAG,IAAI,YAAY,CAAC,GAAG,CAAC,UAAU,GAAG,CAAC,CAAC,CAAC;IACrD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,OAAO,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,WAAW,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAC7E,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,CAAC;AAC9C,CAAC"}
@@ -0,0 +1,55 @@
1
+ import type { CaptionWord } from '@clipkit/protocol';
2
+ import type { TranscriptResult, TranscriptWord } from './types.js';
3
+ export interface ToCaptionWordsOptions {
4
+ /**
5
+ * Seconds of source audio that the caption element's `time` corresponds to —
6
+ * i.e. where the element starts on the timeline, in the audio's clock. Word
7
+ * timings are shifted by `-offset` so they read relative to the element.
8
+ * Default 0 (the caption element starts at the audio's start).
9
+ */
10
+ offset?: number;
11
+ /** Drop words shorter than this many seconds (model noise). Default 0. */
12
+ minDuration?: number;
13
+ }
14
+ /** Map a transcript's words onto a `caption` element's `words[]` (§ protocol). */
15
+ export declare function toCaptionWords(result: TranscriptResult, options?: ToCaptionWordsOptions): CaptionWord[];
16
+ /** Convenience: the full caption-element fields ready to spread into an element. */
17
+ export declare function toCaptionFields(result: TranscriptResult, options?: ToCaptionWordsOptions): {
18
+ type: 'caption';
19
+ words: CaptionWord[];
20
+ };
21
+ /** One caption-sized phrase: where it starts in the audio, plus its words. */
22
+ export interface CaptionSegment {
23
+ /** Absolute start of the segment in the source audio (seconds). */
24
+ start: number;
25
+ /** Words, times RELATIVE to this segment's `start` (ready for a caption element). */
26
+ words: CaptionWord[];
27
+ }
28
+ export interface ToCaptionSegmentsOptions {
29
+ /** Max words per segment. Default 6. */
30
+ maxWords?: number;
31
+ /** A silent gap (seconds) between words at/above this starts a new segment. Default 0.6. */
32
+ maxGap?: number;
33
+ /** Max segment duration (seconds) before forcing a break. Default 3. */
34
+ maxDuration?: number;
35
+ }
36
+ /**
37
+ * Group timed words into caption-sized PHRASES. A new phrase starts when the
38
+ * current one hits `maxWords`, a silent gap ≥ `maxGap` opens, or it exceeds
39
+ * `maxDuration`. Pure and generic — the single source of truth for "how big is
40
+ * a caption segment," shared by transcription and the editor's manual split.
41
+ */
42
+ export declare function segmentWords<T extends {
43
+ start: number;
44
+ end: number;
45
+ }>(words: readonly T[], options?: ToCaptionSegmentsOptions): T[][];
46
+ /**
47
+ * Split a transcript into caption-sized PHRASES — one `caption` element each.
48
+ * A whole-video transcript renders as an unreadable single line; segmenting it
49
+ * into short phrases is how real auto-captions display. Each segment's words are
50
+ * rebased to its own `start`, ready to drop into a `caption` element at
51
+ * `time = mediaStart + segment.start`.
52
+ */
53
+ export declare function toCaptionSegments(result: TranscriptResult, options?: ToCaptionSegmentsOptions): CaptionSegment[];
54
+ export type { TranscriptResult, TranscriptWord };
55
+ //# sourceMappingURL=caption.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"caption.d.ts","sourceRoot":"","sources":["../src/caption.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AACrD,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEnE,MAAM,WAAW,qBAAqB;IACpC;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,0EAA0E;IAC1E,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,kFAAkF;AAClF,wBAAgB,cAAc,CAC5B,MAAM,EAAE,gBAAgB,EACxB,OAAO,GAAE,qBAA0B,GAClC,WAAW,EAAE,CAYf;AAED,oFAAoF;AACpF,wBAAgB,eAAe,CAC7B,MAAM,EAAE,gBAAgB,EACxB,OAAO,GAAE,qBAA0B,GAClC;IAAE,IAAI,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,WAAW,EAAE,CAAA;CAAE,CAE3C;AAED,8EAA8E;AAC9E,MAAM,WAAW,cAAc;IAC7B,mEAAmE;IACnE,KAAK,EAAE,MAAM,CAAC;IACd,qFAAqF;IACrF,KAAK,EAAE,WAAW,EAAE,CAAC;CACtB;AAED,MAAM,WAAW,wBAAwB;IACvC,wCAAwC;IACxC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,4FAA4F;IAC5F,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,wEAAwE;IACxE,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,CAAC,SAAS;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,EACnE,KAAK,EAAE,SAAS,CAAC,EAAE,EACnB,OAAO,GAAE,wBAA6B,GACrC,CAAC,EAAE,EAAE,CAcP;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,gBAAgB,EACxB,OAAO,GAAE,wBAA6B,GACrC,cAAc,EAAE,CASlB;AAED,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,CAAC"}
@@ -0,0 +1,70 @@
1
+ // The protocol bridge — the ONE place transcription meets the Clipkit protocol.
2
+ //
3
+ // A `caption` element's `words` are `{ text, start, end }` with start/end in
4
+ // seconds RELATIVE TO THE ELEMENT'S `time` (PROTOCOL.md §5.x). Transcript words
5
+ // are absolute in the source audio, so mapping is: subtract the element's start
6
+ // offset, clamp to ≥ 0 (the schema requires nonnegative), drop empties.
7
+ //
8
+ // This file imports only the protocol's `CaptionWord` type — no model, no audio.
9
+ // It's pure and the part that's verified against the schema.
10
+ /** Map a transcript's words onto a `caption` element's `words[]` (§ protocol). */
11
+ export function toCaptionWords(result, options = {}) {
12
+ const { offset = 0, minDuration = 0 } = options;
13
+ const out = [];
14
+ for (const w of result.words) {
15
+ const text = w.text.trim();
16
+ if (!text)
17
+ continue;
18
+ const start = Math.max(0, w.start - offset);
19
+ const end = Math.max(start, w.end - offset);
20
+ if (end - start < minDuration)
21
+ continue;
22
+ out.push({ text, start, end });
23
+ }
24
+ return out;
25
+ }
26
+ /** Convenience: the full caption-element fields ready to spread into an element. */
27
+ export function toCaptionFields(result, options = {}) {
28
+ return { type: 'caption', words: toCaptionWords(result, options) };
29
+ }
30
+ /**
31
+ * Group timed words into caption-sized PHRASES. A new phrase starts when the
32
+ * current one hits `maxWords`, a silent gap ≥ `maxGap` opens, or it exceeds
33
+ * `maxDuration`. Pure and generic — the single source of truth for "how big is
34
+ * a caption segment," shared by transcription and the editor's manual split.
35
+ */
36
+ export function segmentWords(words, options = {}) {
37
+ const { maxWords = 6, maxGap = 0.6, maxDuration = 3 } = options;
38
+ const groups = [];
39
+ let cur = [];
40
+ const flush = () => { if (cur.length > 0)
41
+ groups.push(cur); cur = []; };
42
+ for (const w of words) {
43
+ if (cur.length > 0) {
44
+ const prev = cur[cur.length - 1];
45
+ if (cur.length >= maxWords || w.start - prev.end >= maxGap || w.end - cur[0].start > maxDuration)
46
+ flush();
47
+ }
48
+ cur.push(w);
49
+ }
50
+ flush();
51
+ return groups;
52
+ }
53
+ /**
54
+ * Split a transcript into caption-sized PHRASES — one `caption` element each.
55
+ * A whole-video transcript renders as an unreadable single line; segmenting it
56
+ * into short phrases is how real auto-captions display. Each segment's words are
57
+ * rebased to its own `start`, ready to drop into a `caption` element at
58
+ * `time = mediaStart + segment.start`.
59
+ */
60
+ export function toCaptionSegments(result, options = {}) {
61
+ const words = result.words.filter((w) => w.text.trim().length > 0);
62
+ return segmentWords(words, options).map((group) => {
63
+ const base = group[0].start;
64
+ return {
65
+ start: base,
66
+ words: group.map((w) => ({ text: w.text.trim(), start: Math.max(0, w.start - base), end: Math.max(0, w.end - base) })),
67
+ };
68
+ });
69
+ }
70
+ //# sourceMappingURL=caption.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"caption.js","sourceRoot":"","sources":["../src/caption.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,EAAE;AACF,6EAA6E;AAC7E,gFAAgF;AAChF,gFAAgF;AAChF,wEAAwE;AACxE,EAAE;AACF,iFAAiF;AACjF,6DAA6D;AAiB7D,kFAAkF;AAClF,MAAM,UAAU,cAAc,CAC5B,MAAwB,EACxB,UAAiC,EAAE;IAEnC,MAAM,EAAE,MAAM,GAAG,CAAC,EAAE,WAAW,GAAG,CAAC,EAAE,GAAG,OAAO,CAAC;IAChD,MAAM,GAAG,GAAkB,EAAE,CAAC;IAC9B,KAAK,MAAM,CAAC,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;QAC7B,MAAM,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;QAC3B,IAAI,CAAC,IAAI;YAAE,SAAS;QACpB,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,GAAG,MAAM,CAAC,CAAC;QAC5C,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,CAAC,GAAG,GAAG,MAAM,CAAC,CAAC;QAC5C,IAAI,GAAG,GAAG,KAAK,GAAG,WAAW;YAAE,SAAS;QACxC,GAAG,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC,CAAC;IACjC,CAAC;IACD,OAAO,GAA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IAEtC,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IACnE,OAAO,YAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE;QAChD,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAE,CAAC,KAAK,CAAC;QAC7B,OAAO;YACL,KAAK,EAAE,IAAI;YACX,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC,GAAG,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC;SACvH,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,4 @@
1
+ export { transcribe, type TranscribeOptions, type WhisperModel } from './transcribe.js';
2
+ export { toCaptionWords, toCaptionFields, toCaptionSegments, segmentWords, type ToCaptionWordsOptions, type ToCaptionSegmentsOptions, type CaptionSegment } from './caption.js';
3
+ export type { TranscriptResult, TranscriptWord, MonoAudio } from './types.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,UAAU,EAAE,KAAK,iBAAiB,EAAE,KAAK,YAAY,EAAE,MAAM,iBAAiB,CAAC;AACxF,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,iBAAiB,EAAE,YAAY,EAAE,KAAK,qBAAqB,EAAE,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,cAAc,CAAC;AAChL,YAAY,EAAE,gBAAgB,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ // @clipkit/speech-to-text — transcribe an audio/video source into word-
2
+ // timestamped captions. One Whisper model (Transformers.js / ONNX) runs in the
3
+ // browser and in Node; no paid API. The output maps onto the protocol's
4
+ // `caption` element via `toCaptionWords`. Authoring-time only — the runtime
5
+ // never sees this; it just renders the `words[]` we produce.
6
+ //
7
+ // transcribe(audio) → word-timestamped transcript
8
+ // toCaptionWords(result) → caption element words[] (the protocol bridge)
9
+ //
10
+ // Audio decoding is env-specific — import from the matching entry point:
11
+ // Node: import { decodeAudioFile } from '@clipkit/speech-to-text/node';
12
+ // Browser: import { decodeAudioBlob } from '@clipkit/speech-to-text/browser';
13
+ export { transcribe } from './transcribe.js';
14
+ export { toCaptionWords, toCaptionFields, toCaptionSegments, segmentWords } from './caption.js';
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,+EAA+E;AAC/E,wEAAwE;AACxE,4EAA4E;AAC5E,6DAA6D;AAC7D,EAAE;AACF,2DAA2D;AAC3D,8EAA8E;AAC9E,EAAE;AACF,yEAAyE;AACzE,6EAA6E;AAC7E,gFAAgF;AAEhF,OAAO,EAAE,UAAU,EAA6C,MAAM,iBAAiB,CAAC;AACxF,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,iBAAiB,EAAE,YAAY,EAAkF,MAAM,cAAc,CAAC"}
package/dist/node.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { decodeAudioFile } from './audio.node.js';
2
+ export { transcribeFile, type TranscribeFileOptions } from './transcribe-file.node.js';
3
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,KAAK,qBAAqB,EAAE,MAAM,2BAA2B,CAAC"}
package/dist/node.js ADDED
@@ -0,0 +1,6 @@
1
+ // Node entry — `@clipkit/speech-to-text/node`. Audio extraction (ffmpeg) plus
2
+ // the safe one-call `transcribeFile` (worker-isolated). The model engine and the
3
+ // protocol bridge stay env-agnostic on the main export.
4
+ export { decodeAudioFile } from './audio.node.js';
5
+ export { transcribeFile } from './transcribe-file.node.js';
6
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node.js","sourceRoot":"","sources":["../src/node.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,iFAAiF;AACjF,wDAAwD;AAExD,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,OAAO,EAAE,cAAc,EAA8B,MAAM,2BAA2B,CAAC"}
@@ -0,0 +1,16 @@
1
+ import type { TranscriptResult } from './types.js';
2
+ export interface TranscribeFileOptions {
3
+ /** Whisper model id (Hugging Face). Default 'Xenova/whisper-base'. */
4
+ model?: string;
5
+ /** Force a language (e.g. 'en'); omit to auto-detect. */
6
+ language?: string;
7
+ /** Streamed worker stderr (model-download progress lines). */
8
+ onLog?: (line: string) => void;
9
+ }
10
+ /**
11
+ * Transcribe an audio/video file → word-timestamped transcript. Requires
12
+ * `ffmpeg` on PATH. Runs the model in an isolated worker, so a long-running
13
+ * caller (MCP server) stays alive regardless of the model runtime's teardown.
14
+ */
15
+ export declare function transcribeFile(file: string, options?: TranscribeFileOptions): Promise<TranscriptResult>;
16
+ //# sourceMappingURL=transcribe-file.node.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transcribe-file.node.d.ts","sourceRoot":"","sources":["../src/transcribe-file.node.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAInD,MAAM,WAAW,qBAAqB;IACpC,sEAAsE;IACtE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,yDAAyD;IACzD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,8DAA8D;IAC9D,KAAK,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAChC;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,qBAA0B,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAuB3G"}
@@ -0,0 +1,38 @@
1
+ // transcribeFile — the safe, one-call Node entry: decode + transcribe a file,
2
+ // returning a TranscriptResult. The model runs in a worker subprocess so the
3
+ // caller's process is never touched by onnxruntime-node's teardown abort. Both
4
+ // the CLI and the MCP server use this; neither has to know about the quirk.
5
+ import { spawn } from 'node:child_process';
6
+ import { fileURLToPath } from 'node:url';
7
+ const WORKER = fileURLToPath(new URL('./worker.js', import.meta.url));
8
+ /**
9
+ * Transcribe an audio/video file → word-timestamped transcript. Requires
10
+ * `ffmpeg` on PATH. Runs the model in an isolated worker, so a long-running
11
+ * caller (MCP server) stays alive regardless of the model runtime's teardown.
12
+ */
13
+ export function transcribeFile(file, options = {}) {
14
+ const { model, language, onLog } = options;
15
+ return new Promise((resolve, reject) => {
16
+ const child = spawn(process.execPath, [WORKER, JSON.stringify({ file, model, language })], {
17
+ stdio: ['ignore', 'pipe', 'pipe'],
18
+ });
19
+ let out = '';
20
+ child.stdout.on('data', (d) => { out += d.toString(); });
21
+ child.stderr.on('data', (d) => onLog?.(d.toString()));
22
+ child.on('error', reject);
23
+ child.on('close', () => {
24
+ const trimmed = out.trim();
25
+ if (!trimmed) {
26
+ reject(new Error('transcription produced no output (check ffmpeg + the file)'));
27
+ return;
28
+ }
29
+ try {
30
+ resolve(JSON.parse(trimmed));
31
+ }
32
+ catch {
33
+ reject(new Error('transcription output was not valid JSON'));
34
+ }
35
+ });
36
+ });
37
+ }
38
+ //# sourceMappingURL=transcribe-file.node.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transcribe-file.node.js","sourceRoot":"","sources":["../src/transcribe-file.node.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,6EAA6E;AAC7E,+EAA+E;AAC/E,4EAA4E;AAE5E,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAGzC,MAAM,MAAM,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,aAAa,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAWtE;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,IAAY,EAAE,UAAiC,EAAE;IAC9E,MAAM,EAAE,KAAK,EAAE,QAAQ,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IAC3C,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,QAAQ,EAAE,CAAC,CAAC,EAAE;YACzF,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC;SAClC,CAAC,CAAC;QACH,IAAI,GAAG,GAAG,EAAE,CAAC;QACb,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,CAAS,EAAE,EAAE,GAAG,GAAG,IAAI,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACjE,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,CAAS,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;QAC9D,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC1B,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;YACrB,MAAM,OAAO,GAAG,GAAG,CAAC,IAAI,EAAE,CAAC;YAC3B,IAAI,CAAC,OAAO,EAAE,CAAC;gBACb,MAAM,CAAC,IAAI,KAAK,CAAC,4DAA4D,CAAC,CAAC,CAAC;gBAChF,OAAO;YACT,CAAC;YACD,IAAI,CAAC;gBACH,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAqB,CAAC,CAAC;YACnD,CAAC;YAAC,MAAM,CAAC;gBACP,MAAM,CAAC,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC,CAAC;YAC/D,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC"}
@@ -0,0 +1,27 @@
1
+ import type { MonoAudio, TranscriptResult } from './types.js';
2
+ /** Whisper variants — size/speed/accuracy trade-off. `.en` are English-only. */
3
+ export type WhisperModel = 'Xenova/whisper-tiny' | 'Xenova/whisper-tiny.en' | 'Xenova/whisper-base' | 'Xenova/whisper-base.en' | 'Xenova/whisper-small' | 'Xenova/whisper-small.en' | (string & {});
4
+ export interface TranscribeOptions {
5
+ /** Model id (Hugging Face). Default 'Xenova/whisper-base'. */
6
+ model?: WhisperModel;
7
+ /** Force a language (e.g. 'en'); omit to auto-detect. Multilingual models only. */
8
+ language?: string;
9
+ /** Quantized weights — smaller download, slightly lower accuracy. Default true. */
10
+ quantized?: boolean;
11
+ /** Progress callback (model download). `progress` is 0..100 where known. */
12
+ onProgress?: (info: {
13
+ status: string;
14
+ file?: string;
15
+ progress?: number;
16
+ }) => void;
17
+ }
18
+ /**
19
+ * Transcribe 16 kHz mono PCM into a word-timestamped transcript.
20
+ *
21
+ * @example
22
+ * const audio = await decodeAudioFile('clip.mp4'); // from '@clipkit/speech-to-text/node'
23
+ * const result = await transcribe(audio);
24
+ * const words = toCaptionWords(result); // → caption element words[]
25
+ */
26
+ export declare function transcribe(audio: MonoAudio, options?: TranscribeOptions): Promise<TranscriptResult>;
27
+ //# sourceMappingURL=transcribe.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transcribe.d.ts","sourceRoot":"","sources":["../src/transcribe.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,SAAS,EAAE,gBAAgB,EAAkB,MAAM,YAAY,CAAC;AAe9E,gFAAgF;AAChF,MAAM,MAAM,YAAY,GACpB,qBAAqB,GACrB,wBAAwB,GACxB,qBAAqB,GACrB,wBAAwB,GACxB,sBAAsB,GACtB,yBAAyB,GACzB,CAAC,MAAM,GAAG,EAAE,CAAC,CAAC;AAElB,MAAM,WAAW,iBAAiB;IAChC,8DAA8D;IAC9D,KAAK,CAAC,EAAE,YAAY,CAAC;IACrB,mFAAmF;IACnF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mFAAmF;IACnF,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,4EAA4E;IAC5E,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,KAAK,IAAI,CAAC;CACnF;AAoBD;;;;;;;GAOG;AACH,wBAAsB,UAAU,CAC9B,KAAK,EAAE,SAAS,EAChB,OAAO,GAAE,iBAAsB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CA4B3B"}
@@ -0,0 +1,58 @@
1
+ // The transcription engine — Whisper via Transformers.js (ONNX). The SAME model
2
+ // runs in the browser (WebGPU/WASM) and in Node (onnxruntime-node); the library
3
+ // picks the provider for the environment, so this file is env-agnostic.
4
+ //
5
+ // Input is always 16 kHz mono PCM (Float32). Output is a word-timestamped
6
+ // transcript. Map it onto the protocol with `toCaptionWords` (caption.ts).
7
+ import { pipeline as rawPipeline } from '@huggingface/transformers';
8
+ const pipeline = rawPipeline;
9
+ const SAMPLE_RATE = 16000;
10
+ // One cached pipeline per model id — loading is expensive; reuse across calls.
11
+ const pipelines = new Map();
12
+ function getPipeline(model, quantized, onProgress) {
13
+ const key = `${model}:${quantized}`;
14
+ let p = pipelines.get(key);
15
+ if (!p) {
16
+ p = pipeline('automatic-speech-recognition', model, {
17
+ dtype: quantized ? 'q8' : 'fp32',
18
+ progress_callback: onProgress,
19
+ });
20
+ pipelines.set(key, p);
21
+ }
22
+ return p;
23
+ }
24
+ /**
25
+ * Transcribe 16 kHz mono PCM into a word-timestamped transcript.
26
+ *
27
+ * @example
28
+ * const audio = await decodeAudioFile('clip.mp4'); // from '@clipkit/speech-to-text/node'
29
+ * const result = await transcribe(audio);
30
+ * const words = toCaptionWords(result); // → caption element words[]
31
+ */
32
+ export async function transcribe(audio, options = {}) {
33
+ const { model = 'Xenova/whisper-base', language, quantized = true, onProgress } = options;
34
+ if (audio.sampleRate !== SAMPLE_RATE) {
35
+ throw new Error(`transcribe: audio must be ${SAMPLE_RATE} Hz mono (got ${audio.sampleRate} Hz). Decode via '@clipkit/speech-to-text/node' or '/browser'.`);
36
+ }
37
+ const asr = await getPipeline(model, quantized, onProgress);
38
+ const out = await asr(audio.samples, {
39
+ return_timestamps: 'word',
40
+ chunk_length_s: 30,
41
+ stride_length_s: 5,
42
+ language,
43
+ });
44
+ const chunks = out.chunks ?? [];
45
+ const words = chunks.map((c, i) => {
46
+ const start = c.timestamp[0] ?? 0;
47
+ // The last word can have a null end; fall back to the next word's start or +0.3s.
48
+ const end = c.timestamp[1] ?? (chunks[i + 1]?.timestamp[0] ?? start + 0.3);
49
+ return { text: c.text.trim(), start, end };
50
+ }).filter((w) => w.text.length > 0);
51
+ return {
52
+ text: (out?.text ?? '').trim(),
53
+ words,
54
+ language,
55
+ duration: audio.samples.length / SAMPLE_RATE,
56
+ };
57
+ }
58
+ //# sourceMappingURL=transcribe.js.map
@@ -0,0 +1 @@
1
+ {"version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AG,MAAM,WAAW,CAAC,KAAK,EAAE,SAAS,EAAE,UAAU,CAAC,CAAC;IAC5D,MAAM,GAAG,GAAG,MAAM,GAAG,CAAC,KAAK,CAAC,OAAO,EAAE;QACnC,iBAAiB,EAAE,MAAM;QACzB,cAAc,EAAE,EAAE;QAClB,eAAe,EAAE,CAAC;QAClB,QAAQ;KACT,CAAC,CAAC;IAEH,MAAM,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,EAAE,CAAC;IAChC,MAAM,KAAK,GAAqB,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE;QAClD,MAAM,KAAK,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;QAClC,kFAAkF;QAClF,MAAM,GAAG,GAAG,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,IAAI,KAAK,GAAG,GAAG,CAAC,CAAC;QAC3E,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;IAC7C,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAEpC,OAAO;QACL,IAAI,EAAE,CAAC,GAAG,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE;QAC9B,KAAK;QACL,QAAQ;QACR,QAAQ,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,WAAW;KAC7C,CAAC;AACJ,CAAC"}
@@ -0,0 +1,27 @@
1
+ /** One transcribed word with absolute timings in the source audio. */
2
+ export interface TranscriptWord {
3
+ text: string;
4
+ /** Seconds from the start of the transcribed audio. */
5
+ start: number;
6
+ /** Seconds from the start of the transcribed audio. */
7
+ end: number;
8
+ }
9
+ /** The result of transcribing an audio buffer. */
10
+ export interface TranscriptResult {
11
+ /** The full transcript, untimed. */
12
+ text: string;
13
+ /** Word-level transcript with timings. */
14
+ words: TranscriptWord[];
15
+ /** Detected (or forced) BCP-47-ish language code, when the model reports one. */
16
+ language?: string;
17
+ /** Length of the transcribed audio, in seconds. */
18
+ duration: number;
19
+ }
20
+ /** 16 kHz mono PCM — the canonical model input. */
21
+ export interface MonoAudio {
22
+ /** Samples in [-1, 1]. */
23
+ samples: Float32Array;
24
+ /** Sample rate in Hz. MUST be 16000 for the model. */
25
+ sampleRate: number;
26
+ }
27
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAOA,sEAAsE;AACtE,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,uDAAuD;IACvD,KAAK,EAAE,MAAM,CAAC;IACd,uDAAuD;IACvD,GAAG,EAAE,MAAM,CAAC;CACb;AAED,kDAAkD;AAClD,MAAM,WAAW,gBAAgB;IAC/B,oCAAoC;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,0CAA0C;IAC1C,KAAK,EAAE,cAAc,EAAE,CAAC;IACxB,iFAAiF;IACjF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mDAAmD;IACnD,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,mDAAmD;AACnD,MAAM,WAAW,SAAS;IACxB,0BAA0B;IAC1B,OAAO,EAAE,YAAY,CAAC;IACtB,sDAAsD;IACtD,UAAU,EAAE,MAAM,CAAC;CACpB"}
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ // Core transcription types. Environment- and model-agnostic.
2
+ //
3
+ // The audio fed to the model is always 16 kHz mono PCM (Float32, samples in
4
+ // [-1, 1]) — Whisper's canonical input. How you GET there (ffmpeg in Node,
5
+ // WebAudio in the browser) is the only env-specific concern; see `./node` and
6
+ // `./browser`.
7
+ export {};
8
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,6DAA6D;AAC7D,EAAE;AACF,4EAA4E;AAC5E,2EAA2E;AAC3E,8EAA8E;AAC9E,eAAe"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=worker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.d.ts","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":""}
package/dist/worker.js ADDED
@@ -0,0 +1,26 @@
1
+ // Internal worker entry. Runs in its OWN process so onnxruntime-node's harmless
2
+ // `mutex lock failed` teardown abort can never take down the caller (CLI, MCP
3
+ // server, editor build). Decodes + transcribes one file, prints the
4
+ // TranscriptResult as JSON to stdout, then exits. Not a public export — invoked
5
+ // by `transcribeFile` (transcribe-file.node.ts).
6
+ //
7
+ // node dist/worker.js '{"file":"clip.mp4","model":"Xenova/whisper-base"}'
8
+ import { transcribe } from './transcribe.js';
9
+ import { decodeAudioFile } from './audio.node.js';
10
+ const input = JSON.parse(process.argv[2] ?? '{}');
11
+ const audio = await decodeAudioFile(input.file);
12
+ const seen = new Set();
13
+ const result = await transcribe(audio, {
14
+ model: input.model,
15
+ language: input.language,
16
+ // Surface model-download progress on stderr (stdout is reserved for the JSON
17
+ // result); the caller streams these via `transcribeFile`'s onLog.
18
+ onProgress: (i) => {
19
+ if (i.status === 'initiate' && i.file && !seen.has(i.file)) {
20
+ seen.add(i.file);
21
+ process.stderr.write(` ↓ ${i.file}\n`);
22
+ }
23
+ },
24
+ });
25
+ process.stdout.write(JSON.stringify(result), () => process.exit(0));
26
+ //# sourceMappingURL=worker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker.js","sourceRoot":"","sources":["../src/worker.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,8EAA8E;AAC9E,oEAAoE;AACpE,gFAAgF;AAChF,iDAAiD;AACjD,EAAE;AACF,4EAA4E;AAE5E,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAQlD,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,IAAI,CAAgB,CAAC;AACjE,MAAM,KAAK,GAAG,MAAM,eAAe,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;AAChD,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;AAC/B,MAAM,MAAM,GAAG,MAAM,UAAU,CAAC,KAAK,EAAE;IACrC,KAAK,EAAE,KAAK,CAAC,KAAK;IAClB,QAAQ,EAAE,KAAK,CAAC,QAAQ;IACxB,6EAA6E;IAC7E,kEAAkE;IAClE,UAAU,EAAE,CAAC,CAAC,EAAE,EAAE;QAChB,IAAI,CAAC,CAAC,MAAM,KAAK,UAAU,IAAI,CAAC,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC;YAC3D,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;YACjB,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC;QAC1C,CAAC;IACH,CAAC;CACF,CAAC,CAAC;AACH,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC"}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@clipkit/speech-to-text",
3
+ "version": "1.0.0",
4
+ "description": "Speech-to-text for Clipkit — transcribe an audio/video source into word-timestamped captions. Runs the same Whisper model (Transformers.js / ONNX) in the browser (WebGPU/WASM) and in Node (onnxruntime-node); no paid API, no native binaries. The output maps straight onto the protocol's `caption` element `words[]`. Authoring-time only: the runtime stays pure.",
5
+ "license": "Apache-2.0",
6
+ "repository": { "type": "git", "url": "git+https://github.com/clipkit-video/clipkit.git", "directory": "packages/speech-to-text" },
7
+ "homepage": "https://clipkit.dev",
8
+ "bugs": "https://github.com/clipkit-video/clipkit/issues",
9
+ "type": "module",
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "import": "./dist/index.js",
15
+ "types": "./dist/index.d.ts"
16
+ },
17
+ "./caption": {
18
+ "import": "./dist/caption.js",
19
+ "types": "./dist/caption.d.ts"
20
+ },
21
+ "./node": {
22
+ "import": "./dist/node.js",
23
+ "types": "./dist/node.d.ts"
24
+ },
25
+ "./browser": {
26
+ "import": "./dist/audio.browser.js",
27
+ "types": "./dist/audio.browser.d.ts"
28
+ }
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "LICENSE"
34
+ ],
35
+ "scripts": {
36
+ "build": "tsc",
37
+ "dev": "tsc --watch",
38
+ "typecheck": "tsc --noEmit",
39
+ "clean": "rm -rf dist"
40
+ },
41
+ "dependencies": {
42
+ "@clipkit/protocol": "^1.0.0",
43
+ "@huggingface/transformers": "^3.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "@types/node": "^22.0.0",
47
+ "typescript": "^5.7.3"
48
+ }
49
+ }