fablecut 1.16.0 → 1.17.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/CLAUDE.md +188 -3
- package/README.md +24 -10
- package/app.js +768 -19
- package/captions.js +227 -0
- package/delivery.js +22 -2
- package/encoding-profiles.json +26 -0
- package/export-jobs.js +14 -8
- package/index.html +14 -0
- package/mcp-server.js +370 -5
- package/package.json +1 -1
- package/project-ops.js +4 -3
- package/server.js +60 -0
- package/silence.js +97 -0
- package/style.css +167 -4
- package/transcribe-worker.js +39 -0
- package/transcribe.js +294 -0
- package/transcripts.js +78 -0
package/style.css
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
/* ══════════════════ FableCut — Premiere-style dark theme ══════════════════ */
|
|
2
2
|
:root {
|
|
3
|
-
|
|
4
|
-
--
|
|
5
|
-
--panel
|
|
6
|
-
--
|
|
3
|
+
/* surfaces, darkest at the back: app → panels → header bars → controls */
|
|
4
|
+
--bg: #050506;
|
|
5
|
+
--panel: #111115;
|
|
6
|
+
--panel-head: #23232b;
|
|
7
|
+
--panel-sub: #1a1a20;
|
|
8
|
+
--panel-2: #30303a;
|
|
9
|
+
--well: #0a0a0c;
|
|
10
|
+
--border: #2c2c35;
|
|
7
11
|
--text: #d7d7dc;
|
|
8
12
|
--dim: #8b8b93;
|
|
9
13
|
--accent: #7b6cff;
|
|
@@ -2377,6 +2381,22 @@ input[type=range] {
|
|
|
2377
2381
|
box-shadow: inset 0 0 0 1px #ff6b6bcc;
|
|
2378
2382
|
}
|
|
2379
2383
|
|
|
2384
|
+
/* Silences Find marked (Inspector → Silence) — a band over the span, above the clips */
|
|
2385
|
+
.silence-span {
|
|
2386
|
+
position: absolute;
|
|
2387
|
+
top: 2px;
|
|
2388
|
+
bottom: 2px;
|
|
2389
|
+
z-index: 3;
|
|
2390
|
+
pointer-events: none;
|
|
2391
|
+
border-radius: 3px;
|
|
2392
|
+
background: repeating-linear-gradient(
|
|
2393
|
+
45deg,
|
|
2394
|
+
#f5b94233 0 4px,
|
|
2395
|
+
#f5b94214 4px 8px
|
|
2396
|
+
);
|
|
2397
|
+
box-shadow: inset 0 0 0 1px #f5b942aa;
|
|
2398
|
+
}
|
|
2399
|
+
|
|
2380
2400
|
/* ── Clips ── */
|
|
2381
2401
|
.clip {
|
|
2382
2402
|
position: absolute;
|
|
@@ -3635,6 +3655,134 @@ body.file-drag::after {
|
|
|
3635
3655
|
opacity: 0.6;
|
|
3636
3656
|
}
|
|
3637
3657
|
|
|
3658
|
+
/* Transcript tab: the timeline's words; click to go, select and Delete to cut */
|
|
3659
|
+
.tr-page {
|
|
3660
|
+
flex: 1;
|
|
3661
|
+
min-height: 0;
|
|
3662
|
+
display: flex;
|
|
3663
|
+
flex-direction: column;
|
|
3664
|
+
}
|
|
3665
|
+
|
|
3666
|
+
.tr-head {
|
|
3667
|
+
padding: 10px 10px 6px;
|
|
3668
|
+
border-bottom: 1px solid var(--border);
|
|
3669
|
+
display: flex;
|
|
3670
|
+
flex-direction: column;
|
|
3671
|
+
gap: 6px;
|
|
3672
|
+
}
|
|
3673
|
+
|
|
3674
|
+
.tr-row {
|
|
3675
|
+
display: flex;
|
|
3676
|
+
gap: 6px;
|
|
3677
|
+
align-items: center;
|
|
3678
|
+
flex-wrap: wrap;
|
|
3679
|
+
}
|
|
3680
|
+
|
|
3681
|
+
.tr-row select, .tr-row input[type="search"] {
|
|
3682
|
+
background: var(--panel);
|
|
3683
|
+
border: 1px solid var(--border);
|
|
3684
|
+
border-radius: 5px;
|
|
3685
|
+
color: var(--text);
|
|
3686
|
+
font: 11px "Segoe UI", sans-serif;
|
|
3687
|
+
padding: 3px 6px;
|
|
3688
|
+
min-width: 0;
|
|
3689
|
+
}
|
|
3690
|
+
|
|
3691
|
+
.tr-row select { flex: 1 1 0; max-width: 140px; }
|
|
3692
|
+
.tr-row input[type="search"] { flex: 1; min-width: 90px; padding: 4px 8px; }
|
|
3693
|
+
.tr-row select:focus, .tr-row input[type="search"]:focus { outline: none; border-color: var(--accent); }
|
|
3694
|
+
|
|
3695
|
+
.tr-lbl {
|
|
3696
|
+
font-size: 11px;
|
|
3697
|
+
color: var(--dim);
|
|
3698
|
+
white-space: nowrap;
|
|
3699
|
+
}
|
|
3700
|
+
|
|
3701
|
+
.tr-count {
|
|
3702
|
+
font-size: 11px;
|
|
3703
|
+
color: var(--dim);
|
|
3704
|
+
white-space: nowrap;
|
|
3705
|
+
}
|
|
3706
|
+
|
|
3707
|
+
.tr-busy {
|
|
3708
|
+
display: flex;
|
|
3709
|
+
gap: 8px;
|
|
3710
|
+
align-items: center;
|
|
3711
|
+
font-size: 11px;
|
|
3712
|
+
color: var(--dim);
|
|
3713
|
+
}
|
|
3714
|
+
|
|
3715
|
+
.tr-busy > span:first-child { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
3716
|
+
|
|
3717
|
+
.tr-bar {
|
|
3718
|
+
width: 60px;
|
|
3719
|
+
height: 4px;
|
|
3720
|
+
border-radius: 2px;
|
|
3721
|
+
background: var(--panel-2);
|
|
3722
|
+
overflow: hidden;
|
|
3723
|
+
}
|
|
3724
|
+
|
|
3725
|
+
.tr-bar i {
|
|
3726
|
+
display: block;
|
|
3727
|
+
height: 100%;
|
|
3728
|
+
width: 0;
|
|
3729
|
+
background: var(--accent);
|
|
3730
|
+
transition: width 0.2s;
|
|
3731
|
+
}
|
|
3732
|
+
|
|
3733
|
+
.tr-body {
|
|
3734
|
+
flex: 1;
|
|
3735
|
+
min-height: 0;
|
|
3736
|
+
overflow-y: auto;
|
|
3737
|
+
padding: 8px 12px 16px;
|
|
3738
|
+
font-size: 13px;
|
|
3739
|
+
line-height: 1.7;
|
|
3740
|
+
outline: none;
|
|
3741
|
+
}
|
|
3742
|
+
|
|
3743
|
+
.tr-seg { margin: 0 0 10px; }
|
|
3744
|
+
|
|
3745
|
+
.tr-tc {
|
|
3746
|
+
display: inline-block;
|
|
3747
|
+
margin-right: 6px;
|
|
3748
|
+
font-size: 10px;
|
|
3749
|
+
font-variant-numeric: tabular-nums;
|
|
3750
|
+
color: var(--dim);
|
|
3751
|
+
cursor: pointer;
|
|
3752
|
+
}
|
|
3753
|
+
|
|
3754
|
+
.tr-tc:hover { color: var(--text); }
|
|
3755
|
+
|
|
3756
|
+
.tw {
|
|
3757
|
+
cursor: pointer;
|
|
3758
|
+
border-radius: 3px;
|
|
3759
|
+
padding: 1px 0;
|
|
3760
|
+
user-select: none;
|
|
3761
|
+
}
|
|
3762
|
+
|
|
3763
|
+
.tw:hover { background: var(--panel-2); }
|
|
3764
|
+
.tw.hit { background: rgba(255, 209, 102, 0.22); }
|
|
3765
|
+
.tw.now { color: #fff; box-shadow: inset 0 -2px 0 var(--accent); }
|
|
3766
|
+
.tw.sel { background: rgba(123, 108, 255, 0.45); color: #fff; }
|
|
3767
|
+
|
|
3768
|
+
.tr-empty, .tr-note {
|
|
3769
|
+
font-size: 12px;
|
|
3770
|
+
color: var(--dim);
|
|
3771
|
+
margin: 6px 0 10px;
|
|
3772
|
+
}
|
|
3773
|
+
|
|
3774
|
+
.tr-foot {
|
|
3775
|
+
display: flex;
|
|
3776
|
+
gap: 8px;
|
|
3777
|
+
align-items: center;
|
|
3778
|
+
padding: 6px 10px;
|
|
3779
|
+
border-top: 1px solid var(--border);
|
|
3780
|
+
font-size: 11px;
|
|
3781
|
+
color: var(--dim);
|
|
3782
|
+
}
|
|
3783
|
+
|
|
3784
|
+
.tr-foot > span { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
3785
|
+
|
|
3638
3786
|
.cp-head {
|
|
3639
3787
|
display: flex;
|
|
3640
3788
|
gap: 6px;
|
|
@@ -4342,3 +4490,18 @@ a.btn { text-decoration: none; }
|
|
|
4342
4490
|
margin: 8px 0 2px;
|
|
4343
4491
|
font-size: 12px;
|
|
4344
4492
|
}
|
|
4493
|
+
|
|
4494
|
+
/* ══ Surface levels: each layer of the layout its own tone, so the structure
|
|
4495
|
+
reads at a glance — the app background, then panel bodies, then the header
|
|
4496
|
+
bars and toolbars on top of each panel, then the controls; the timeline's
|
|
4497
|
+
lanes sit in a darker well under their track headers and ruler. ══ */
|
|
4498
|
+
body { background: var(--bg); }
|
|
4499
|
+
.topbar { background: var(--panel-sub); }
|
|
4500
|
+
.bin-tabs, .tr-head, .cp-head { background: var(--panel-sub); }
|
|
4501
|
+
.panel-head, .bin-tabs.side-tabs, .timeline-toolbar { background: var(--panel-head); border-radius: 8px 8px 0 0; } /* the side tabs are also .bin-tabs */
|
|
4502
|
+
.btn:hover { background-color: #3a3a46; }
|
|
4503
|
+
.track-headers, .track-head { background: #1c1c23; }
|
|
4504
|
+
.ruler { background: #2a2a33; }
|
|
4505
|
+
.tracks-content, .timeline-scroll { background-color: var(--well); }
|
|
4506
|
+
.track:nth-child(even):not(.drop-hint) { background-color: #ffffff05; } /* a drop target keeps its highlight */
|
|
4507
|
+
.insp-section { background: var(--panel-sub); border-radius: 6px; padding: 8px 10px; margin: 0 0 10px; }
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/* FableCut speech-to-text worker (a module worker started by the editor).
|
|
2
|
+
|
|
3
|
+
Runs Whisper with transformers.js, imported from the CDN URL the editor
|
|
4
|
+
passes (transcribe.js LIBRARY) only when something is transcribed; the
|
|
5
|
+
library and the model files are cached by the browser after the first time.
|
|
6
|
+
One piece of audio at a time (≤ 30 s, 16 kHz mono, planned by
|
|
7
|
+
transcribe.js), so the editor can report progress and stop between pieces.
|
|
8
|
+
|
|
9
|
+
in: {type:"run", id, lib, model, pcm: Float32Array, language: "en" | null}
|
|
10
|
+
out: {type:"progress", status, file, loaded, total} — while the model downloads
|
|
11
|
+
{type:"done", id, chunks:[{text, timestamp:[s, e]}]} · {type:"error", id, error} */
|
|
12
|
+
let asr = null, asrModel = "";
|
|
13
|
+
|
|
14
|
+
async function load(lib, model) {
|
|
15
|
+
if (asr && asrModel === model) return asr;
|
|
16
|
+
const T = await import(lib);
|
|
17
|
+
T.env.allowLocalModels = false;
|
|
18
|
+
asr = await T.pipeline("automatic-speech-recognition", model, {
|
|
19
|
+
dtype: "q8", device: "wasm",
|
|
20
|
+
progress_callback: (p) => {
|
|
21
|
+
if (!p || (p.status !== "progress" && p.status !== "initiate" && p.status !== "done")) return;
|
|
22
|
+
self.postMessage({ type: "progress", status: p.status, file: p.file || "", loaded: p.loaded || 0, total: p.total || 0 });
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
asrModel = model;
|
|
26
|
+
return asr;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
self.onmessage = async (e) => {
|
|
30
|
+
const m = e.data || {};
|
|
31
|
+
if (m.type !== "run") return;
|
|
32
|
+
try {
|
|
33
|
+
const run = await load(m.lib, m.model);
|
|
34
|
+
const out = await run(m.pcm, { return_timestamps: "word", ...(m.language ? { language: m.language, task: "transcribe" } : {}) });
|
|
35
|
+
self.postMessage({ type: "done", id: m.id, chunks: (out && out.chunks) || [] });
|
|
36
|
+
} catch (err) {
|
|
37
|
+
self.postMessage({ type: "error", id: m.id, error: String((err && err.message) || err) });
|
|
38
|
+
}
|
|
39
|
+
};
|
package/transcribe.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
/* FableCut transcribe — words with times, from speech, onto the timeline.
|
|
2
|
+
Zero dependencies; loaded by the editor as a plain script (global
|
|
3
|
+
`FableCutTranscribe`) and required by the server and the MCP server, so
|
|
4
|
+
the Transcript tab and `fablecut_transcribe` read, find and cut the same
|
|
5
|
+
words with the same `extract` ops.
|
|
6
|
+
|
|
7
|
+
Speech is turned into words in the browser (transcribe-worker.js runs
|
|
8
|
+
Whisper with transformers.js, fetched from a CDN the first time and cached).
|
|
9
|
+
Here: plan (where to split long audio, at its quietest moments) → joinChunks
|
|
10
|
+
(Whisper's word pieces → [text, start, end] in file seconds) → a transcript
|
|
11
|
+
document per file → clipWords / layout (onto the timeline through each
|
|
12
|
+
clip's in point and speed) → find (a phrase, matched on word boundaries,
|
|
13
|
+
case and punctuation ignored) → cutSpans (the time to cut: the words and
|
|
14
|
+
the pause after them, on whole frames) → cutOps (one extract per span, last
|
|
15
|
+
first, so earlier times stay put). */
|
|
16
|
+
(function (root, factory) {
|
|
17
|
+
const api = factory();
|
|
18
|
+
if (typeof module === "object" && module.exports) module.exports = api;
|
|
19
|
+
else root.FableCutTranscribe = api;
|
|
20
|
+
})(typeof self !== "undefined" ? self : this, function () {
|
|
21
|
+
"use strict";
|
|
22
|
+
|
|
23
|
+
/** Whisper models with word timestamps (cross-attention alignment), 8-bit, from Hugging Face. */
|
|
24
|
+
const MODELS = {
|
|
25
|
+
base: { id: "onnx-community/whisper-base_timestamped", label: "Base", mb: 77 },
|
|
26
|
+
small: { id: "onnx-community/whisper-small_timestamped", label: "Small", mb: 250 },
|
|
27
|
+
};
|
|
28
|
+
const DEFAULT_MODEL = "base";
|
|
29
|
+
/** transformers.js, pinned. Fetched by the worker only when something is transcribed. */
|
|
30
|
+
const LIBRARY = "https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.1/dist/transformers.min.js";
|
|
31
|
+
/** Whisper listens at 16 kHz, mono. */
|
|
32
|
+
const RATE = 16000;
|
|
33
|
+
/** Languages offered by name (Whisper knows more; any of its codes works). */
|
|
34
|
+
const LANGUAGES = {
|
|
35
|
+
en: "English", es: "Spanish", fr: "French", de: "German", it: "Italian", pt: "Portuguese", nl: "Dutch",
|
|
36
|
+
sv: "Swedish", no: "Norwegian", da: "Danish", fi: "Finnish", pl: "Polish", cs: "Czech", sk: "Slovak",
|
|
37
|
+
ro: "Romanian", hu: "Hungarian", el: "Greek", bg: "Bulgarian", hr: "Croatian", sr: "Serbian",
|
|
38
|
+
uk: "Ukrainian", ru: "Russian", tr: "Turkish", ar: "Arabic", he: "Hebrew", fa: "Persian", ur: "Urdu",
|
|
39
|
+
hi: "Hindi", bn: "Bengali", pa: "Punjabi", gu: "Gujarati", mr: "Marathi", ta: "Tamil", te: "Telugu",
|
|
40
|
+
kn: "Kannada", ml: "Malayalam", zh: "Chinese", ja: "Japanese", ko: "Korean", vi: "Vietnamese",
|
|
41
|
+
th: "Thai", id: "Indonesian", ms: "Malay", tl: "Tagalog", sw: "Swahili",
|
|
42
|
+
};
|
|
43
|
+
/** Every language code Whisper takes. */
|
|
44
|
+
const WHISPER_LANGS = new Set(("en zh de es ru ko fr ja pt tr pl ca nl ar sv it id hi fi vi he uk el ms cs ro da hu ta no th ur hr bg lt la mi ml cy sk te fa lv bn sr az sl kn et mk br eu is hy ne mn bs kk sq sw gl mr pa si km sn yo so af oc ka be tg sd gu am yi lo uz fo ht ps tk nn mt sa lb my bo tl mg as tt haw ln ha ba jw su yue").split(" "));
|
|
45
|
+
const MAX_WORDS = 200000;
|
|
46
|
+
const MAX_WORD = 80;
|
|
47
|
+
/** edit-ops.js MIN_DUR: extract refuses a range this short or shorter. */
|
|
48
|
+
const MIN_CUT = 0.05;
|
|
49
|
+
|
|
50
|
+
const r3 = (x) => Math.round(x * 1000) / 1000 || 0;
|
|
51
|
+
const r4 = (x) => Math.round(x * 10000) / 10000 || 0; // as the editor stores times; never -0
|
|
52
|
+
const num = (x) => typeof x === "number" && Number.isFinite(x);
|
|
53
|
+
|
|
54
|
+
/** The model key, defaulted and checked. */
|
|
55
|
+
function model(m) {
|
|
56
|
+
const k = m == null || m === "" ? DEFAULT_MODEL : String(m);
|
|
57
|
+
if (!MODELS[k]) throw new Error(`model must be ${Object.keys(MODELS).join(" or ")}`);
|
|
58
|
+
return k;
|
|
59
|
+
}
|
|
60
|
+
/** A language code for Whisper, or null to let it detect the language. */
|
|
61
|
+
function language(l) {
|
|
62
|
+
if (l == null || l === "" || l === "auto") return null;
|
|
63
|
+
const k = String(l).trim().toLowerCase();
|
|
64
|
+
if (WHISPER_LANGS.has(k)) return k;
|
|
65
|
+
const byName = Object.keys(LANGUAGES).find((c) => LANGUAGES[c].toLowerCase() === k);
|
|
66
|
+
if (byName) return byName;
|
|
67
|
+
throw new Error(`language must be a Whisper language code such as en, es, hi or ja (or auto), not ${JSON.stringify(l)}`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Where to split `pcm` (mono samples at `rate`) into pieces Whisper takes in one go (≤ 30 s):
|
|
71
|
+
* each piece ends at the quietest 50 ms between `min` and `max` seconds in, so no word is cut
|
|
72
|
+
* in half. Returns [[startSample, endSample], …] covering the whole of it. */
|
|
73
|
+
function plan(pcm, rate = RATE, { min = 12, max = 28 } = {}) {
|
|
74
|
+
const n = pcm.length, hop = Math.max(1, Math.round(rate * 0.05));
|
|
75
|
+
const out = [];
|
|
76
|
+
let a = 0;
|
|
77
|
+
while (n - a > max * rate) {
|
|
78
|
+
const lo = a + Math.round(min * rate), hi = a + Math.round(max * rate) - hop;
|
|
79
|
+
let best = hi, bestE = Infinity;
|
|
80
|
+
for (let f = lo; f <= hi; f += hop) {
|
|
81
|
+
let e = 0;
|
|
82
|
+
for (let i = f; i < f + hop; i++) e += pcm[i] * pcm[i];
|
|
83
|
+
if (e <= bestE) { bestE = e; best = f; } // ties go later: longer pieces, fewer calls
|
|
84
|
+
}
|
|
85
|
+
const b = best + (hop >> 1);
|
|
86
|
+
out.push([a, b]);
|
|
87
|
+
a = b;
|
|
88
|
+
}
|
|
89
|
+
if (n > a || !out.length) out.push([a, n]);
|
|
90
|
+
return out;
|
|
91
|
+
}
|
|
92
|
+
/** True when a piece is too quiet to hold speech (Whisper invents words in silence). */
|
|
93
|
+
function quiet(pcm, a = 0, b = pcm.length, floorDb = -55) {
|
|
94
|
+
if (b <= a) return true;
|
|
95
|
+
let e = 0;
|
|
96
|
+
for (let i = a; i < b; i++) e += pcm[i] * pcm[i];
|
|
97
|
+
const rms = Math.sqrt(e / (b - a));
|
|
98
|
+
return !(rms > 0) || 20 * Math.log10(rms) < floorDb;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const SCRIPT_NO_SPACES = /[-ヿ㐀-鿿豈---က-႟ក-]/;
|
|
102
|
+
/** Whisper's word pieces ({text, timestamp:[s, e]}) → words [text, start, end] in file seconds
|
|
103
|
+
* (`offset` added). A piece without a leading space continues the word before it
|
|
104
|
+
* ("studio" ".fablecut" → "studio.fablecut"), except in scripts written without spaces. */
|
|
105
|
+
function joinChunks(chunks, offset = 0, end = Infinity) {
|
|
106
|
+
const out = [];
|
|
107
|
+
for (const ch of chunks || []) {
|
|
108
|
+
const raw = String(ch && ch.text != null ? ch.text : "");
|
|
109
|
+
const t = raw.trim().replace(/\s+/g, " ");
|
|
110
|
+
if (!t) continue;
|
|
111
|
+
const ts = (ch && ch.timestamp) || [];
|
|
112
|
+
const last = out[out.length - 1];
|
|
113
|
+
let s = num(ts[0]) ? ts[0] + offset : last ? last[2] : offset;
|
|
114
|
+
if (last && s < last[1]) s = last[1];
|
|
115
|
+
let e = num(ts[1]) ? ts[1] + offset : s + 0.3;
|
|
116
|
+
e = Math.min(Math.max(e, s), end);
|
|
117
|
+
s = Math.min(s, e);
|
|
118
|
+
if (last && !/^\s/.test(raw) && !SCRIPT_NO_SPACES.test(t)) {
|
|
119
|
+
last[0] = (last[0] + t).slice(0, MAX_WORD);
|
|
120
|
+
last[2] = r3(Math.max(last[2], e));
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
out.push([t.slice(0, MAX_WORD), r3(s), r3(e)]);
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** A transcript document, checked: {v, src, model, language, duration, created, words:[[text, s, e], …]}.
|
|
129
|
+
* Throws on anything malformed. Words are kept in time order, inside 0…duration. */
|
|
130
|
+
function validate(doc) {
|
|
131
|
+
if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new Error("a transcript must be an object");
|
|
132
|
+
if (!Array.isArray(doc.words)) throw new Error("a transcript needs words: [[text, start, end], …]");
|
|
133
|
+
if (doc.words.length > MAX_WORDS) throw new Error(`a transcript holds at most ${MAX_WORDS} words`);
|
|
134
|
+
const duration = num(doc.duration) && doc.duration > 0 ? doc.duration : null;
|
|
135
|
+
const words = [];
|
|
136
|
+
let prev = 0;
|
|
137
|
+
for (const w of doc.words) {
|
|
138
|
+
if (!Array.isArray(w) || typeof w[0] !== "string" || !num(w[1]) || !num(w[2])) throw new Error("each word must be [text, start, end]");
|
|
139
|
+
const t = w[0].trim().slice(0, MAX_WORD);
|
|
140
|
+
if (!t) continue;
|
|
141
|
+
let s = Math.max(0, w[1], prev), e = Math.max(s, w[2]);
|
|
142
|
+
if (duration != null) { s = Math.min(s, duration); e = Math.min(e, duration); }
|
|
143
|
+
words.push([t, r3(s), r3(e)]);
|
|
144
|
+
prev = s;
|
|
145
|
+
}
|
|
146
|
+
const lang = doc.language == null ? null : String(doc.language).slice(0, 16);
|
|
147
|
+
return {
|
|
148
|
+
v: 1, src: typeof doc.src === "string" ? doc.src.slice(0, 1024) : null,
|
|
149
|
+
model: typeof doc.model === "string" ? doc.model.slice(0, 64) : null,
|
|
150
|
+
language: lang, duration: duration != null ? r3(duration) : null,
|
|
151
|
+
created: typeof doc.created === "string" ? doc.created.slice(0, 40) : new Date().toISOString(),
|
|
152
|
+
words,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** A clip whose speed follows keyframes: its words can't be placed on the timeline from one speed. */
|
|
157
|
+
const ramped = (c) => !!(c && c.keyframes && Array.isArray(c.keyframes.speed) && c.keyframes.speed.length);
|
|
158
|
+
const clipSpeed = (c) => { const v = +(c && c.props && c.props.speed); return v > 0 ? v : 1; };
|
|
159
|
+
|
|
160
|
+
/** The words a clip plays, on the timeline: [{w, s, e, clip, r:[clipStart, clipEnd]}]. A word
|
|
161
|
+
* counts when its middle is inside the clip's window of the file. Empty for a speed ramp. */
|
|
162
|
+
function clipWords(clip, words) {
|
|
163
|
+
if (!clip || ramped(clip) || !Array.isArray(words)) return [];
|
|
164
|
+
const speed = clipSpeed(clip), a = +clip.in || 0, b = a + (+clip.duration || 0) * speed;
|
|
165
|
+
const start = +clip.start || 0, r = [r4(start), r4(start + (+clip.duration || 0))];
|
|
166
|
+
let lo = 0, hi = words.length;
|
|
167
|
+
while (lo < hi) { const m = (lo + hi) >> 1; if (words[m][2] < a) lo = m + 1; else hi = m; }
|
|
168
|
+
const out = [];
|
|
169
|
+
for (let i = lo; i < words.length; i++) {
|
|
170
|
+
const [w, s, e] = words[i];
|
|
171
|
+
const mid = (s + e) / 2;
|
|
172
|
+
if (mid > b) break;
|
|
173
|
+
if (mid < a) continue;
|
|
174
|
+
out.push({ w, s: r4(start + (Math.max(s, a) - a) / speed), e: r4(start + (Math.min(e, b) - a) / speed), clip: clip.id, r });
|
|
175
|
+
}
|
|
176
|
+
return out;
|
|
177
|
+
}
|
|
178
|
+
/** Every clip's words on one timeline, in time order: entries [{clip, words}] → words as clipWords. */
|
|
179
|
+
function layout(entries) {
|
|
180
|
+
const all = [];
|
|
181
|
+
for (const { clip, words } of entries || []) all.push(...clipWords(clip, words));
|
|
182
|
+
return all.sort((x, y) => x.s - y.s || x.e - y.e);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** A word reduced for matching: lower case, letters and digits only. */
|
|
186
|
+
const norm = (t) => String(t).toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^\p{L}\p{N}]+/gu, "");
|
|
187
|
+
|
|
188
|
+
/** Where `query` is said: [{i, j}] (first and last word index), left to right, never overlapping.
|
|
189
|
+
* Case, accents, punctuation and spacing are ignored ("A.I. powered" finds "AI-powered"), and a
|
|
190
|
+
* match starts and ends on word boundaries ("cat" doesn't find "category"). */
|
|
191
|
+
function find(words, query, { limit = 1000 } = {}) {
|
|
192
|
+
const q = norm(query);
|
|
193
|
+
if (!q) return [];
|
|
194
|
+
let text = "";
|
|
195
|
+
const startAt = new Map(), endAt = new Map(); // char offset → word index
|
|
196
|
+
for (let i = 0; i < words.length; i++) {
|
|
197
|
+
const n = norm(words[i].w != null ? words[i].w : words[i][0]);
|
|
198
|
+
if (!n) continue;
|
|
199
|
+
startAt.set(text.length, i);
|
|
200
|
+
text += n;
|
|
201
|
+
endAt.set(text.length, i);
|
|
202
|
+
}
|
|
203
|
+
const out = [];
|
|
204
|
+
let from = 0;
|
|
205
|
+
while (out.length < limit) {
|
|
206
|
+
const k = text.indexOf(q, from);
|
|
207
|
+
if (k < 0) break;
|
|
208
|
+
if (startAt.has(k) && endAt.has(k + q.length)) {
|
|
209
|
+
out.push({ i: startAt.get(k), j: endAt.get(k + q.length) });
|
|
210
|
+
from = k + q.length;
|
|
211
|
+
} else from = k + 1;
|
|
212
|
+
}
|
|
213
|
+
return out;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Union of {from, to} spans, sorted. */
|
|
217
|
+
function union(list) {
|
|
218
|
+
const out = [];
|
|
219
|
+
for (const s of list.filter((x) => x.to > x.from).sort((x, y) => x.from - y.from)) {
|
|
220
|
+
const last = out[out.length - 1];
|
|
221
|
+
if (last && s.from <= last.to + 1e-6) last.to = Math.max(last.to, s.to);
|
|
222
|
+
else out.push({ from: s.from, to: s.to });
|
|
223
|
+
}
|
|
224
|
+
return out;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The timeline time to cut for word runs [{i, j}] of timeline words (layout): from just before
|
|
228
|
+
* the first word to just before the word that follows (so the pause after goes too, and the
|
|
229
|
+
* pause before stays), never into a neighbouring word, inside the clip, on whole frames.
|
|
230
|
+
* Returns [{from, to}] in time order, merged where they touch. */
|
|
231
|
+
function cutSpans(words, runs, { fps = 30, lead = 0.04, tail = 0.12 } = {}) {
|
|
232
|
+
const frame = 1 / Math.max(1, +fps || 30);
|
|
233
|
+
const same = (x, y) => x && y && x.r[0] === y.r[0] && x.r[1] === y.r[1];
|
|
234
|
+
const spans = [];
|
|
235
|
+
for (const { i, j } of runs) {
|
|
236
|
+
const a = words[i], b = words[j];
|
|
237
|
+
if (!a || !b || j < i) continue;
|
|
238
|
+
const prev = same(words[i - 1], a) ? words[i - 1] : null, next = same(words[j + 1], b) ? words[j + 1] : null;
|
|
239
|
+
const floor = prev ? prev.e : a.r[0], ceil = next ? next.s : b.r[1];
|
|
240
|
+
const from = Math.max(floor, a.s - lead);
|
|
241
|
+
const to = next ? Math.max(b.e, Math.min(ceil, next.s - lead)) : Math.min(ceil, b.e + tail);
|
|
242
|
+
let f = Math.ceil((from - 1e-6) / frame) * frame, t = Math.floor((to + 1e-6) / frame) * frame;
|
|
243
|
+
if (f > a.s + 1e-6) f = Math.max(floor, Math.floor((a.s + 1e-6) / frame) * frame); // don't leave the word's first frame
|
|
244
|
+
if (f < floor - 1e-6) f = Math.ceil((floor - 1e-6) / frame) * frame;
|
|
245
|
+
if (t < b.e - 1e-6 && Math.ceil((b.e - 1e-6) / frame) * frame <= ceil + 1e-6) t = Math.ceil((b.e - 1e-6) / frame) * frame;
|
|
246
|
+
const span = { from: r4(f), to: r4(t) };
|
|
247
|
+
if (span.to - span.from > Math.max(frame - 1e-4, MIN_CUT)) spans.push(span);
|
|
248
|
+
}
|
|
249
|
+
return union(spans).map((s) => ({ from: r4(s.from), to: r4(s.to) }));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Patch ops that cut the spans out, last first. `tracks` limits the lanes
|
|
253
|
+
* (default: the targeted tracks), `force` cuts through locked material. */
|
|
254
|
+
function cutOps(spans, { tracks = null, force = false } = {}) {
|
|
255
|
+
return spans.slice().sort((x, y) => y.from - x.from).map((s) => ({
|
|
256
|
+
op: "extract", from: s.from, to: s.to,
|
|
257
|
+
...(Array.isArray(tracks) && tracks.length ? { tracks: tracks.slice() } : {}),
|
|
258
|
+
...(force ? { force: true } : {}),
|
|
259
|
+
}));
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Words i…j as text. */
|
|
263
|
+
function text(words, i = 0, j = words.length - 1) {
|
|
264
|
+
const out = [];
|
|
265
|
+
for (let k = Math.max(0, i); k <= Math.min(j, words.length - 1); k++) out.push(words[k].w != null ? words[k].w : words[k][0]);
|
|
266
|
+
return out.join(" ");
|
|
267
|
+
}
|
|
268
|
+
/** A word that ends a sentence ("done." "why?"), but not an abbreviation like "A.I." or "U.S.". */
|
|
269
|
+
const sentenceEnd = (t) => /[.!?…。!?]["')\]]?$/.test(t) && !/^(\p{L}\.)+$/u.test(t);
|
|
270
|
+
/** Readable lines: a break after a sentence (once a line is `min` s long), at a pause of `gap` s,
|
|
271
|
+
* or at `max` s — not at a cut, so an edited passage still reads as one. [{i, j, from, to, text}] */
|
|
272
|
+
function segments(words, { gap = 0.8, min = 2.5, max = 10 } = {}) {
|
|
273
|
+
const out = [];
|
|
274
|
+
let i0 = 0;
|
|
275
|
+
for (let k = 0; k < words.length; k++) {
|
|
276
|
+
const w = words[k], nx = words[k + 1];
|
|
277
|
+
const s = w.s != null ? w.s : w[1], e = w.e != null ? w.e : w[2];
|
|
278
|
+
const s0 = words[i0].s != null ? words[i0].s : words[i0][1];
|
|
279
|
+
const t = w.w != null ? w.w : w[0];
|
|
280
|
+
const ns = nx ? (nx.s != null ? nx.s : nx[1]) : null;
|
|
281
|
+
const brk = !nx || ns - e >= gap || e - s0 >= max || (sentenceEnd(t) && e - s0 >= min);
|
|
282
|
+
if (brk) { out.push({ i: i0, j: k, from: s0, to: e, text: text(words, i0, k) }); i0 = k + 1; }
|
|
283
|
+
}
|
|
284
|
+
return out;
|
|
285
|
+
}
|
|
286
|
+
/** Seconds the spans add up to. */
|
|
287
|
+
const total = (spans) => r4(spans.reduce((n, s) => n + (s.to - s.from), 0));
|
|
288
|
+
|
|
289
|
+
return {
|
|
290
|
+
MODELS, DEFAULT_MODEL, LIBRARY, RATE, LANGUAGES, MIN_CUT,
|
|
291
|
+
model, language, plan, quiet, joinChunks, validate, ramped, clipWords, layout, norm, find, union,
|
|
292
|
+
cutSpans, cutOps, text, segments, total,
|
|
293
|
+
};
|
|
294
|
+
});
|
package/transcripts.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/* Transcripts on disk, one per version of a file: analysis/transcripts/
|
|
2
|
+
<stem>-<hash of its path>-<hash of its size and mtime>.json, holding the
|
|
3
|
+
document transcribe.js validates ({v, src, model, language, duration,
|
|
4
|
+
created, words:[[text, start, end], …]}, times in file seconds). A cache,
|
|
5
|
+
like the proxies: a re-rendered or replaced file simply has no transcript
|
|
6
|
+
until it is transcribed again, and saving a new one drops the old ones.
|
|
7
|
+
|
|
8
|
+
createTranscripts({dir, resolveSrc}) → {
|
|
9
|
+
get(src) → the document | false (none for this version of the file) | null (no such file)
|
|
10
|
+
info(src) → {words, language, model, duration, created} | false | null — without the words
|
|
11
|
+
put(src, doc) → the document as saved (validated; throws on a bad one or a missing file)
|
|
12
|
+
remove(src) → true when one was deleted
|
|
13
|
+
}
|
|
14
|
+
Zero dependencies. */
|
|
15
|
+
"use strict";
|
|
16
|
+
const crypto = require("crypto");
|
|
17
|
+
const fs = require("fs");
|
|
18
|
+
const path = require("path");
|
|
19
|
+
const T = require("./transcribe.js");
|
|
20
|
+
|
|
21
|
+
const hash = (s) => crypto.createHash("sha1").update(s).digest("hex").slice(0, 10);
|
|
22
|
+
|
|
23
|
+
function createTranscripts({ dir, resolveSrc }) {
|
|
24
|
+
/** "<stem>-<path hash>-" (every version of the file) and the full name of this version. */
|
|
25
|
+
function names(file) {
|
|
26
|
+
const st = fs.statSync(file);
|
|
27
|
+
const stem = path.basename(file, path.extname(file)).replace(/[^\w\-]+/g, "_").slice(0, 40) || "media";
|
|
28
|
+
const prefix = `${stem}-${hash(path.resolve(file))}-`;
|
|
29
|
+
return { prefix, name: `${prefix}${hash(st.size + "|" + Math.round(st.mtimeMs))}.json` };
|
|
30
|
+
}
|
|
31
|
+
function read(src) {
|
|
32
|
+
const file = resolveSrc(src);
|
|
33
|
+
if (!file) return null;
|
|
34
|
+
let n;
|
|
35
|
+
try { n = names(file); } catch { return null; }
|
|
36
|
+
try { return JSON.parse(fs.readFileSync(path.join(dir, n.name), "utf8")); } catch { return false; }
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
get(src) {
|
|
40
|
+
const d = read(src);
|
|
41
|
+
if (!d) return d;
|
|
42
|
+
try { return T.validate(d); } catch { return false; }
|
|
43
|
+
},
|
|
44
|
+
info(src) {
|
|
45
|
+
const d = this.get(src);
|
|
46
|
+
if (!d) return d;
|
|
47
|
+
return { words: d.words.length, language: d.language, model: d.model, duration: d.duration, created: d.created };
|
|
48
|
+
},
|
|
49
|
+
put(src, doc) {
|
|
50
|
+
const file = resolveSrc(src);
|
|
51
|
+
if (!file) throw Object.assign(new Error("no such file: " + src), { code: 404 });
|
|
52
|
+
const clean = T.validate({ ...doc, src });
|
|
53
|
+
const { prefix, name } = names(file);
|
|
54
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
55
|
+
const tmp = path.join(dir, name + ".tmp-" + process.pid);
|
|
56
|
+
fs.writeFileSync(tmp, JSON.stringify(clean));
|
|
57
|
+
fs.renameSync(tmp, path.join(dir, name));
|
|
58
|
+
// earlier versions of the file keep nothing worth reading
|
|
59
|
+
for (const old of fs.readdirSync(dir)) if (old !== name && old.startsWith(prefix) && old.endsWith(".json")) {
|
|
60
|
+
try { fs.unlinkSync(path.join(dir, old)); } catch { }
|
|
61
|
+
}
|
|
62
|
+
return clean;
|
|
63
|
+
},
|
|
64
|
+
remove(src) {
|
|
65
|
+
const file = resolveSrc(src);
|
|
66
|
+
if (!file) return false;
|
|
67
|
+
let prefix;
|
|
68
|
+
try { prefix = names(file).prefix; } catch { return false; }
|
|
69
|
+
let n = 0;
|
|
70
|
+
let list = [];
|
|
71
|
+
try { list = fs.readdirSync(dir); } catch { }
|
|
72
|
+
for (const f of list) if (f.startsWith(prefix) && f.endsWith(".json")) { try { fs.unlinkSync(path.join(dir, f)); n++; } catch { } }
|
|
73
|
+
return n > 0;
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
module.exports = { createTranscripts };
|