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/mcp-server.js
CHANGED
|
@@ -274,6 +274,70 @@ const TOOLS = [
|
|
|
274
274
|
required: ["clipIds"],
|
|
275
275
|
},
|
|
276
276
|
},
|
|
277
|
+
{
|
|
278
|
+
name: "fablecut_silence",
|
|
279
|
+
description: "Find the silences in speech and, with cut:true, cut them out. Listens to the given clips (a video's linked audio stems, after channel routing, gain and volume) and reports every stretch where none of them is above `threshold` for at least `minSilence` seconds, keeping `padding` seconds of quiet beside each phrase so words aren't clipped. Gaps between clips are left alone. With cut:true each silence is removed with an `extract` on the targeted tracks (or `tracks`), last first, in one revision: later material moves up, linked stems stay in sync, locked tracks and clips stay put — lock the music bed first if it should keep running. A version is saved before the cut. Without cut it only reports, so check the spans (and fablecut_frame them) first. The same as the inspector's Silence section. Needs ffmpeg + ffprobe on PATH.",
|
|
280
|
+
inputSchema: {
|
|
281
|
+
type: "object",
|
|
282
|
+
properties: {
|
|
283
|
+
clipIds: { type: "array", items: { type: "string" }, description: "The speech clips to listen to (a video clip brings its linked stems)" },
|
|
284
|
+
threshold: { type: "number", description: "Below this level (dBFS) counts as silence, -80…-10 (default -40; raise it toward -30 for a noisy room)" },
|
|
285
|
+
minSilence: { type: "number", description: "Shortest silence to report or cut, seconds 0.1…10 (default 0.5)" },
|
|
286
|
+
padding: { type: "number", description: "Quiet kept beside each phrase, seconds 0…2 (default 0.15)" },
|
|
287
|
+
cut: { type: "boolean", description: "Cut the silences out (default false: only report them)" },
|
|
288
|
+
tracks: { type: "array", items: { type: "string" }, description: "cut: the lanes to cut on (default: the targeted tracks)" },
|
|
289
|
+
force: { type: "boolean", description: "cut: also cut through locked clips (only when the user asked)" },
|
|
290
|
+
},
|
|
291
|
+
required: ["clipIds"],
|
|
292
|
+
},
|
|
293
|
+
},
|
|
294
|
+
{
|
|
295
|
+
name: "fablecut_transcribe",
|
|
296
|
+
description: "What is said, word by word, with times — and text-based editing. Transcribes the clips' speech with Whisper in the editor (an open tab, else headless Chrome / Edge; the speech model downloads once, the audio never leaves the machine), keeps one transcript per file (analysis/transcripts/), and answers with the timeline's words as timed lines (timeline seconds), so you can read an interview, pick the good takes, or find where something is said. find:\"phrase\" (or a list) reports every place it is said — case, punctuation and spacing ignored, whole words only — with the exact span; cut:true then extracts each of them on the targeted tracks (or `tracks`), the words and the pause after them, last first, in one revision: later material moves up, linked stems stay in sync, locked clips stay put (lock the music bed first). A version is saved before a cut. Files already transcribed aren't done again unless again:true. Default clips: every video / audio clip with sound on the open timeline. mediaIds reads whole files instead (file seconds; no cut). The same as the editor's Transcript tab.",
|
|
297
|
+
inputSchema: {
|
|
298
|
+
type: "object",
|
|
299
|
+
properties: {
|
|
300
|
+
clipIds: { type: "array", items: { type: "string" }, description: "Clips to transcribe and read (a video brings its linked stems). Default: every clip with sound on the timeline" },
|
|
301
|
+
mediaIds: { type: "array", items: { type: "string" }, description: "Instead of clips: whole files, read in file seconds (find works, cut doesn't)" },
|
|
302
|
+
model: { type: "string", enum: ["base", "small"], description: "Whisper model: base (default, 77 MB, quick) or small (250 MB, more accurate, slower)" },
|
|
303
|
+
language: { type: "string", description: "The spoken language as a Whisper code (en, es, hi, ja, …) or auto (default: detected)" },
|
|
304
|
+
again: { type: "boolean", description: "Transcribe again even when a transcript exists (another model or language)" },
|
|
305
|
+
find: { anyOf: [{ type: "string" }, { type: "array", items: { type: "string" } }], description: "A word or phrase (or several) to find; matches are reported with their timeline spans" },
|
|
306
|
+
from: { type: "number", description: "Only words from this time on (timeline seconds; file seconds with mediaIds)" },
|
|
307
|
+
to: { type: "number", description: "Only words before this time" },
|
|
308
|
+
cut: { type: "boolean", description: "Cut every match of `find` out (default false: only report)" },
|
|
309
|
+
tracks: { type: "array", items: { type: "string" }, description: "cut: the lanes to cut on (default: the targeted tracks)" },
|
|
310
|
+
force: { type: "boolean", description: "cut: also cut through locked clips (only when the user asked)" },
|
|
311
|
+
where: { type: "string", enum: ["auto", "tab", "headless"], description: "Where to transcribe: auto (default): an open editor tab, else headless · tab · headless" },
|
|
312
|
+
timeout: { type: "number", description: "Seconds to wait for the transcription (default 1800)" },
|
|
313
|
+
},
|
|
314
|
+
},
|
|
315
|
+
},
|
|
316
|
+
{
|
|
317
|
+
name: "fablecut_captions",
|
|
318
|
+
description: "Captions from what is said: makes caption clips on the timeline from the clips' transcripts (transcribing first when there is none, like fablecut_transcribe), each one a text clip with `wordTimes` so its words follow the speech. Captions are cut at pauses and sentences, one or two lines as wide as the canvas allows. Styles: subtitle (plain, on a dark bar), karaoke (words light up as they are said), highlight (bold, the word being said in a colour — the reel look), pop (one to three big words at a time, each popping in). They go on the lane captions are already on, else the top video lane, else a new lane above it, and replace the captions there (replace:false keeps them). export:\"srt\"|\"vtt\" writes the timeline's captions to a subtitle file in exports/; import: a path to an SRT / WebVTT file (or its text) places its captions instead of the transcript's. remove:true deletes the captions. Captions are text clips: restyle them with updateClip, and make them after the cutting is done (a cut through a caption doesn't re-time its words — run this again). The same as the Transcript tab's Captions row.",
|
|
319
|
+
inputSchema: {
|
|
320
|
+
type: "object",
|
|
321
|
+
properties: {
|
|
322
|
+
style: { type: "string", enum: ["subtitle", "karaoke", "highlight", "pop"], description: "The look (default subtitle)" },
|
|
323
|
+
clipIds: { type: "array", items: { type: "string" }, description: "Caption only these clips' speech (default: every clip with sound)" },
|
|
324
|
+
from: { type: "number", description: "Only speech from this time on (timeline seconds)" },
|
|
325
|
+
to: { type: "number", description: "Only speech before this time" },
|
|
326
|
+
lines: { type: "number", description: "Lines per caption, 1–3 (default: the style's)" },
|
|
327
|
+
words: { type: "number", description: "At most this many words per caption (pop and highlight have their own default)" },
|
|
328
|
+
size: { type: "number", description: "Scale the style's text size, e.g. 1.2 (default 1)" },
|
|
329
|
+
track: { type: "string", description: "The video lane to put them on (default: chosen as described)" },
|
|
330
|
+
replace: { type: "boolean", description: "Remove the captions already on the timeline first (default true)" },
|
|
331
|
+
export: { type: "string", enum: ["srt", "vtt"], description: "Write the timeline's captions to exports/ as SubRip or WebVTT, and change nothing" },
|
|
332
|
+
import: { type: "string", description: "An SRT or WebVTT file (absolute path, or a /media/… src) or its text: place its captions" },
|
|
333
|
+
remove: { type: "boolean", description: "Delete every caption clip" },
|
|
334
|
+
force: { type: "boolean", description: "Also replace or remove locked captions (only when the user asked)" },
|
|
335
|
+
model: { type: "string", enum: ["base", "small"], description: "Transcribing first: the Whisper model (see fablecut_transcribe)" },
|
|
336
|
+
language: { type: "string", description: "Transcribing first: the spoken language (default: detected)" },
|
|
337
|
+
where: { type: "string", enum: ["auto", "tab", "headless"], description: "Transcribing first: where (see fablecut_transcribe)" },
|
|
338
|
+
},
|
|
339
|
+
},
|
|
340
|
+
},
|
|
277
341
|
{
|
|
278
342
|
name: "fablecut_denoise",
|
|
279
343
|
description: "Reduce background noise (hiss, hum, room tone) on audio clips: ffmpeg's FFT denoiser renders a cleaned FLAC of each clip's whole source file into media/, and the clip — with its linked stems — switches to it (the picture keeps its own file, so links and timing stay intact). The same as the inspector's Noise control. amount 'off' switches back to the original. Re-running reuses a file already rendered. Needs ffmpeg + ffprobe on PATH. Refuses locked clips unless force:true.",
|
|
@@ -493,19 +557,314 @@ async function measureClipGroup(proj, clips) {
|
|
|
493
557
|
return meter ? meter.result() : null;
|
|
494
558
|
}
|
|
495
559
|
/** Timeline spans with sound on these voice clips (ducking.js pipeline). */
|
|
496
|
-
async function voiceRegions(proj, voices, threshold) {
|
|
560
|
+
async function voiceRegions(proj, voices, threshold, minLen, heard) {
|
|
497
561
|
const L = require("./loudness.js"), D = require("./ducking.js");
|
|
498
562
|
const lists = [];
|
|
499
563
|
for (const v of voices) {
|
|
500
564
|
let env = null;
|
|
501
565
|
await streamClipAudio(proj, v, (nCh) => { env = new D.EnvelopeMeter(nCh, NORM_SR); },
|
|
502
566
|
(chs) => env.push(L.routeChannels(chs, v.props || {})));
|
|
503
|
-
if (!env) continue;
|
|
567
|
+
if (!env) continue; // no audio stream
|
|
568
|
+
if (heard) heard.add(v.id);
|
|
504
569
|
const sp = Math.min(8, Math.max(0.1, +v.props?.speed || 1));
|
|
505
570
|
const gain = Math.pow(10, (+v.props?.gain || 0) / 20) * Math.min(2, Math.max(0, +(v.props?.volume ?? 1)));
|
|
506
|
-
lists.push(D.activeRegions(env.result(), { t0: v.start, speed: sp, gain, threshold }));
|
|
571
|
+
lists.push(D.activeRegions(env.result(), { t0: v.start, speed: sp, gain, threshold, ...(minLen != null ? { minLen } : {}) }));
|
|
572
|
+
}
|
|
573
|
+
return D.mergeRegions(lists, minLen != null ? 0 : undefined);
|
|
574
|
+
}
|
|
575
|
+
/** The clips that carry a selection's sound, one list per linked group: its
|
|
576
|
+
* audio stems, else the clip itself (audio, or a video without stems). */
|
|
577
|
+
function speechGroups(proj, ids) {
|
|
578
|
+
const groups = new Map();
|
|
579
|
+
for (const id of ids) {
|
|
580
|
+
const c = proj.clips.find((x) => x.id === id);
|
|
581
|
+
if (!c) throw new Error("no clip " + id);
|
|
582
|
+
if (c.kind !== "audio" && c.kind !== "video") throw new Error(`clip ${id} is ${c.kind} — no sound to listen to`);
|
|
583
|
+
const key = c.linkGroup || c.id;
|
|
584
|
+
if (groups.has(key)) continue;
|
|
585
|
+
const members = c.linkGroup ? proj.clips.filter((x) => x.linkGroup === c.linkGroup) : [c];
|
|
586
|
+
const stems = members.filter((x) => x.kind === "audio");
|
|
587
|
+
groups.set(key, stems.length ? stems : [c]);
|
|
507
588
|
}
|
|
508
|
-
return
|
|
589
|
+
return [...groups.values()];
|
|
590
|
+
}
|
|
591
|
+
const fmtClock = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(2).padStart(5, "0")}`;
|
|
592
|
+
const fmtDur = (s) => { const t = Math.round(s); return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`; };
|
|
593
|
+
/* fablecut_silence: silence.js on the clips' sound, then (cut:true) its extract ops. */
|
|
594
|
+
async function silenceTool(args) {
|
|
595
|
+
const S = require("./silence.js");
|
|
596
|
+
const ids = Array.isArray(args.clipIds) ? args.clipIds.map(String) : [];
|
|
597
|
+
if (!ids.length) throw new Error("`clipIds` must list the speech clip(s) to listen to");
|
|
598
|
+
const opts = S.options(args);
|
|
599
|
+
const doc = readProject();
|
|
600
|
+
const readRev = doc.revision || 0;
|
|
601
|
+
const groups = speechGroups(doc, ids);
|
|
602
|
+
const disabled = new Set(Array.isArray(doc.disabledTracks) ? doc.disabledTracks : []);
|
|
603
|
+
const enabled = groups.map((g) => g.filter((x) => !disabled.has(x.track) && x.disabled !== true)).filter((g) => g.length);
|
|
604
|
+
if (!enabled.length) throw new Error("those clips are disabled (or on disabled tracks) — nothing to listen to");
|
|
605
|
+
// a speed ramp moves the sound along the timeline unevenly: those clips are left alone
|
|
606
|
+
const live = enabled.filter((g) => !g.some(S.ramped));
|
|
607
|
+
const rampedN = enabled.length - live.length;
|
|
608
|
+
if (!live.length) throw new Error("those clips have a speed ramp (speed keyframes) — silence removal works on clips at a steady speed");
|
|
609
|
+
const heard = new Set();
|
|
610
|
+
const sound = await voiceRegions(doc, live.flat(), opts.threshold, S.MIN_SOUND, heard);
|
|
611
|
+
// only time that was actually listened to can be silent: a clip with no audio stream is left alone
|
|
612
|
+
const usable = live.filter((g) => g.every((x) => heard.has(x.id)));
|
|
613
|
+
if (!usable.length) throw new Error("those clips have no audio stream — nothing to listen to");
|
|
614
|
+
const ranges = usable.map((g) => [Math.min(...g.map((x) => x.start)), Math.max(...g.map((x) => x.start + x.duration))]);
|
|
615
|
+
const spans = S.silentSpans(sound, ranges, { ...opts, fps: doc.fps });
|
|
616
|
+
const listen = S.union(ranges).reduce((n, [a, b]) => n + b - a, 0);
|
|
617
|
+
const head = `${spans.length} silence${spans.length === 1 ? "" : "s"}, ${S.total(spans).toFixed(1)} s of ${fmtDur(listen)} ` +
|
|
618
|
+
`(threshold ${opts.threshold} dBFS, at least ${opts.minSilence} s, ${opts.padding} s kept beside speech` +
|
|
619
|
+
(usable.length < live.length ? `; ${live.length - usable.length} clip(s) with no audio stream left alone` : "") +
|
|
620
|
+
(rampedN ? `; ${rampedN} clip(s) with a speed ramp left alone` : "") + ")";
|
|
621
|
+
const list = spans.slice(0, 60).map((s) => ` ${fmtClock(s.from)} → ${fmtClock(s.to)} (${(s.to - s.from).toFixed(2)} s)`)
|
|
622
|
+
.concat(spans.length > 60 ? [` … +${spans.length - 60} more`] : []);
|
|
623
|
+
if (args.cut !== true) return [head + (spans.length ? ":" : "."), ...list,
|
|
624
|
+
...(spans.length ? ["Nothing cut yet: call again with cut:true to remove them (lock the music bed first if it should keep running)."] : [])].join("\n");
|
|
625
|
+
if (!spans.length) return head + " — nothing to cut.";
|
|
626
|
+
// the timeline must be the one that was listened to
|
|
627
|
+
const proj = readProject();
|
|
628
|
+
if ((proj.revision || 0) !== readRev)
|
|
629
|
+
throw new Error(`the project changed while listening (revision ${readRev} → ${proj.revision}) — nothing cut; run fablecut_silence again`);
|
|
630
|
+
const end = (p) => p.clips.reduce((m, c) => Math.max(m, c.start + c.duration), 0);
|
|
631
|
+
const before = end(proj);
|
|
632
|
+
ProjectOps.applyPatch(proj, S.cutOps(spans, { tracks: args.tracks, force: args.force === true }), { savedItems });
|
|
633
|
+
// a cut this size always keeps the project as it was, not once per session like other edits
|
|
634
|
+
let verWarn = "";
|
|
635
|
+
try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before cutting silences"); }
|
|
636
|
+
catch (e) { verWarn = ` Warning: no version was saved before the cut (${e.message}).`; }
|
|
637
|
+
let diskRev = readRev;
|
|
638
|
+
try { diskRev = readProject().revision || 0; } catch {}
|
|
639
|
+
if (diskRev !== readRev) throw new Error(`the project changed while cutting (revision ${readRev} → ${diskRev}) — nothing cut; run fablecut_silence again`);
|
|
640
|
+
proj.revision = readRev + 1;
|
|
641
|
+
writeProject(proj);
|
|
642
|
+
lastReadRevision = proj.revision;
|
|
643
|
+
return `Cut ${head} — timeline ${fmtDur(before)} → ${fmtDur(end(proj))} (revision ${proj.revision}). UI hot-reloaded.` +
|
|
644
|
+
(verWarn || ` The project as it was is kept as a version (fablecut_versions lists it; restore undoes the cut).`);
|
|
645
|
+
}
|
|
646
|
+
/** What words are placed by and cuts land on: where each clip sits and plays from, the track
|
|
647
|
+
* switches and the frame rate. An editor saving probed media details while a transcription runs
|
|
648
|
+
* doesn't change it; a moved, trimmed or cut clip does. */
|
|
649
|
+
function timelineSig(doc) {
|
|
650
|
+
return JSON.stringify([doc.fps, doc.lockedTracks || [], doc.untargetedTracks || [], doc.disabledTracks || [],
|
|
651
|
+
(doc.clips || []).map((c) => [c.id, c.track, c.start, c.in, c.duration, c.mediaId, c.props?.speed ?? 1, c.keyframes?.speed ?? null, !!c.locked, !!c.disabled])]);
|
|
652
|
+
}
|
|
653
|
+
/* The words said on the timeline (or in whole files, mediaIds): transcribes what has no
|
|
654
|
+
transcript yet as a job in an open tab, else headless, then lays the words out. Shared by
|
|
655
|
+
fablecut_transcribe and fablecut_captions. */
|
|
656
|
+
async function speechWords(args, fileMode) {
|
|
657
|
+
const T = require("./transcribe.js");
|
|
658
|
+
const model = T.model(args.model), language = T.language(args.language);
|
|
659
|
+
const doc = readProject();
|
|
660
|
+
const readRev = doc.revision || 0;
|
|
661
|
+
const mediaById = new Map((doc.media || []).map((m) => [m.id, m]));
|
|
662
|
+
const disabled = new Set(Array.isArray(doc.disabledTracks) ? doc.disabledTracks : []);
|
|
663
|
+
let entries = [], files = [], rampedN = 0;
|
|
664
|
+
if (fileMode) {
|
|
665
|
+
for (const id of args.mediaIds.map(String)) {
|
|
666
|
+
const m = mediaById.get(id);
|
|
667
|
+
if (!m) throw new Error("no media " + id);
|
|
668
|
+
if (m.kind !== "audio" && m.kind !== "video") throw new Error(`media ${id} is ${m.kind} — no sound to transcribe`);
|
|
669
|
+
files.push(m);
|
|
670
|
+
}
|
|
671
|
+
} else {
|
|
672
|
+
const ids = Array.isArray(args.clipIds) && args.clipIds.length ? args.clipIds.map(String)
|
|
673
|
+
: doc.clips.filter((c) => (c.kind === "audio" || c.kind === "video") && mediaById.get(c.mediaId) && mediaById.get(c.mediaId).audioChannels !== 0
|
|
674
|
+
// a picture whose sound is on linked stems (they are read instead), or one with its sound off
|
|
675
|
+
&& !(c.kind === "video" && (c.linkGroup ? doc.clips.some((x) => x.linkGroup === c.linkGroup && x.kind === "audio") : +(c.props?.volume ?? 1) === 0))).map((c) => c.id);
|
|
676
|
+
if (!ids.length) throw new Error("the timeline has no clips with sound — add some, or pass mediaIds");
|
|
677
|
+
const groups = speechGroups(doc, ids).map((g) => g.filter((x) => !disabled.has(x.track) && x.disabled !== true)).filter((g) => g.length);
|
|
678
|
+
if (!groups.length) throw new Error("those clips are disabled (or on disabled tracks) — nothing to read");
|
|
679
|
+
for (const g of groups) {
|
|
680
|
+
if (g.some(T.ramped)) { rampedN++; continue; }
|
|
681
|
+
const m = mediaById.get(g[0].mediaId);
|
|
682
|
+
if (m) entries.push({ clip: g[0], media: m });
|
|
683
|
+
}
|
|
684
|
+
if (!entries.length) throw new Error("those clips have a speed ramp (speed keyframes) — their words can't be placed on the timeline");
|
|
685
|
+
files = [...new Map(entries.map((e) => [e.media.src, e.media])).values()];
|
|
686
|
+
}
|
|
687
|
+
if (!(await ensureUIServer())) throw new Error(`the editor server is not running and could not be started on port ${PORT}`);
|
|
688
|
+
const srcs = files.map((m) => m.src);
|
|
689
|
+
const st = await apiJSON("POST", "/api/transcript/status", { srcs });
|
|
690
|
+
if (st.status !== 200) throw new Error(st.body?.error || "could not read the transcripts");
|
|
691
|
+
const gone = srcs.filter((s) => st.body.status[s] === null);
|
|
692
|
+
if (gone.length) throw new Error("these files are missing (offline): " + gone.join(", "));
|
|
693
|
+
const todo = args.again === true ? srcs : srcs.filter((s) => !st.body.status[s]);
|
|
694
|
+
let note = "";
|
|
695
|
+
if (todo.length) {
|
|
696
|
+
const r = await apiJSON("POST", "/api/transcribe/request", { where: args.where || "auto", transcribe: { srcs: todo, model, language, again: args.again === true } });
|
|
697
|
+
if (r.status !== 200) throw new Error(r.body?.error || `transcribe request failed (${r.status})`);
|
|
698
|
+
let job = r.body;
|
|
699
|
+
const deadline = Date.now() + 1000 * (Number.isFinite(args.timeout) && args.timeout > 0 ? args.timeout : 1800);
|
|
700
|
+
while (job.status === "pending" || job.status === "running") {
|
|
701
|
+
if (Date.now() > deadline) {
|
|
702
|
+
await apiJSON("POST", "/api/export/job/cancel?id=" + encodeURIComponent(job.id));
|
|
703
|
+
throw new Error("timed out waiting for the transcription — try fewer clips, or a larger timeout");
|
|
704
|
+
}
|
|
705
|
+
await sleep(1000);
|
|
706
|
+
const q = await apiJSON("GET", "/api/export/job?id=" + encodeURIComponent(job.id));
|
|
707
|
+
if (q.status !== 200) throw new Error(q.body?.error || "lost track of the transcription job");
|
|
708
|
+
job = q.body;
|
|
709
|
+
}
|
|
710
|
+
if (job.status !== "done") throw new Error(`transcription ${job.status}: ${job.error || "no reason given"}`);
|
|
711
|
+
const res = job.result || {};
|
|
712
|
+
note = `Transcribed ${(res.done || []).length} file${(res.done || []).length === 1 ? "" : "s"} (${model}${language ? ", " + language : ""}, in ${job.via === "headless" ? "a headless browser" : "the open editor tab"})` +
|
|
713
|
+
((res.failed || []).length ? `; failed: ${res.failed.map((f) => `${f.src} (${f.error})`).join(", ")}` : "") + ".\n";
|
|
714
|
+
}
|
|
715
|
+
const docs = new Map();
|
|
716
|
+
for (const src of srcs) {
|
|
717
|
+
const g = await apiJSON("GET", "/api/transcript?src=" + encodeURIComponent(src));
|
|
718
|
+
if (g.status === 200 && g.body?.transcript) docs.set(src, T.validate(g.body.transcript));
|
|
719
|
+
}
|
|
720
|
+
const langs = [...new Set([...docs.values()].map((d) => d.language === "auto" ? "detected" : d.language).filter(Boolean))];
|
|
721
|
+
const without = srcs.filter((s) => !docs.has(s));
|
|
722
|
+
let words, scope;
|
|
723
|
+
if (fileMode) {
|
|
724
|
+
// file seconds, one file after another
|
|
725
|
+
words = [];
|
|
726
|
+
for (const m of files) { const d = docs.get(m.src); if (d) words.push(...d.words.map(([w, s, e]) => ({ w, s, e, clip: m.id, r: [0, d.duration || e] }))); }
|
|
727
|
+
scope = `${files.length} file${files.length === 1 ? "" : "s"} (file seconds)`;
|
|
728
|
+
} else {
|
|
729
|
+
words = T.layout(entries.filter((e) => docs.has(e.media.src)).map((e) => ({ clip: e.clip, words: docs.get(e.media.src).words })));
|
|
730
|
+
scope = `${entries.length} clip${entries.length === 1 ? "" : "s"} on the timeline (timeline seconds)`;
|
|
731
|
+
}
|
|
732
|
+
return { doc, readRev, sig: timelineSig(doc), words, scope, note, langs, without, rampedN };
|
|
733
|
+
}
|
|
734
|
+
/* fablecut_transcribe: transcripts from the editor (a job), read on the timeline, found, cut. */
|
|
735
|
+
async function transcribeTool(args) {
|
|
736
|
+
const T = require("./transcribe.js");
|
|
737
|
+
const model = T.model(args.model), language = T.language(args.language);
|
|
738
|
+
const finds = (args.find == null ? [] : Array.isArray(args.find) ? args.find : [args.find]).map(String).filter((q) => T.norm(q));
|
|
739
|
+
if (args.find != null && !finds.length) throw new Error("find needs a word or phrase with letters or digits in it");
|
|
740
|
+
const fileMode = Array.isArray(args.mediaIds) && args.mediaIds.length;
|
|
741
|
+
if (args.cut === true && !finds.length) throw new Error("cut:true needs find — the words or phrases to cut");
|
|
742
|
+
if (args.cut === true && fileMode) throw new Error("cut works on the timeline — pass clipIds (or nothing), not mediaIds");
|
|
743
|
+
const { doc, sig, words, scope, note, langs, without, rampedN } = await speechWords(args, fileMode);
|
|
744
|
+
const fmtT = (x) => fmtClock(Math.max(0, x));
|
|
745
|
+
const lo = Number.isFinite(args.from) ? args.from : -Infinity, hi = Number.isFinite(args.to) ? args.to : Infinity;
|
|
746
|
+
const inWin = (w) => w.e >= lo && w.s <= hi;
|
|
747
|
+
const head = note + `${words.filter(inWin).length} words, ${scope}` + (langs.length ? `, language ${langs.join("/")}` : "") +
|
|
748
|
+
(without.length ? `; no transcript for ${without.join(", ")}` : "") + (rampedN ? `; ${rampedN} clip(s) with a speed ramp left out` : "");
|
|
749
|
+
if (!finds.length) {
|
|
750
|
+
const segs = T.segments(words).filter((sg) => sg.to >= lo && sg.from <= hi);
|
|
751
|
+
const MAX = 300;
|
|
752
|
+
const lines = segs.slice(0, MAX).map((sg) => `[${fmtT(sg.from)}] ${sg.text}`);
|
|
753
|
+
return [head + (segs.length ? ":" : "."), ...lines,
|
|
754
|
+
...(segs.length > MAX ? [`… ${segs.length - MAX} more lines — pass from (e.g. ${segs[MAX].from.toFixed(1)}) to read on`] : []),
|
|
755
|
+
...(segs.length ? ["find:\"…\" locates a phrase; with cut:true it is cut out."] : [])].join("\n");
|
|
756
|
+
}
|
|
757
|
+
// find (and cut)
|
|
758
|
+
const runs = [], report = [];
|
|
759
|
+
for (const q of finds) {
|
|
760
|
+
const hits = T.find(words, q).filter((r) => inWin(words[r.i]) && inWin(words[r.j]));
|
|
761
|
+
const spans = T.cutSpans(words, hits, { fps: doc.fps });
|
|
762
|
+
report.push(`"${q}": ${hits.length} match${hits.length === 1 ? "" : "es"}` + (hits.length ? ":" : ""));
|
|
763
|
+
for (const r of hits.slice(0, 50)) {
|
|
764
|
+
const ctx = `${T.text(words, Math.max(0, r.i - 4), r.i - 1)} «${T.text(words, r.i, r.j)}» ${T.text(words, r.j + 1, Math.min(words.length - 1, r.j + 4))}`.trim();
|
|
765
|
+
report.push(` ${fmtT(words[r.i].s)} → ${fmtT(words[r.j].e)} ${ctx}`);
|
|
766
|
+
}
|
|
767
|
+
if (hits.length > 50) report.push(` … +${hits.length - 50} more`);
|
|
768
|
+
runs.push(...hits);
|
|
769
|
+
if (!spans.length && hits.length) report.push(" (each is too short to cut on its own)");
|
|
770
|
+
}
|
|
771
|
+
const spans = T.cutSpans(words, runs, { fps: doc.fps });
|
|
772
|
+
if (args.cut !== true) return [head + ".", ...report,
|
|
773
|
+
...(spans.length && !fileMode ? [`Cutting them would remove ${spans.length} span${spans.length === 1 ? "" : "s"}, ${T.total(spans).toFixed(1)} s (the words and the pause after each): call again with cut:true.`] : [])].join("\n");
|
|
774
|
+
if (!spans.length) return [head + ".", ...report, "Nothing to cut."].join("\n");
|
|
775
|
+
const proj = readProject(), readRev = proj.revision || 0;
|
|
776
|
+
if (timelineSig(proj) !== sig)
|
|
777
|
+
throw new Error("the timeline changed while transcribing (a clip was moved, trimmed or cut) — nothing cut; run fablecut_transcribe again");
|
|
778
|
+
const end = (p) => p.clips.reduce((m, c) => Math.max(m, c.start + c.duration), 0);
|
|
779
|
+
const before = end(proj);
|
|
780
|
+
ProjectOps.applyPatch(proj, T.cutOps(spans, { tracks: args.tracks, force: args.force === true }), { savedItems });
|
|
781
|
+
let verWarn = "";
|
|
782
|
+
try { createHistory({ projects: createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR }) }).beforeAgent("Before cutting words"); }
|
|
783
|
+
catch (e) { verWarn = ` Warning: no version was saved before the cut (${e.message}).`; }
|
|
784
|
+
let diskRev = readRev;
|
|
785
|
+
try { diskRev = readProject().revision || 0; } catch {}
|
|
786
|
+
if (diskRev !== readRev) throw new Error(`the project changed while cutting (revision ${readRev} → ${diskRev}) — nothing cut; run fablecut_transcribe again`);
|
|
787
|
+
proj.revision = readRev + 1;
|
|
788
|
+
writeProject(proj);
|
|
789
|
+
lastReadRevision = proj.revision;
|
|
790
|
+
return [head + ".", ...report,
|
|
791
|
+
`Cut ${spans.length} span${spans.length === 1 ? "" : "s"}, ${T.total(spans).toFixed(1)} s — timeline ${fmtDur(before)} → ${fmtDur(end(proj))} (revision ${proj.revision}). UI hot-reloaded.` +
|
|
792
|
+
(verWarn || " The project as it was is kept as a version (fablecut_versions lists it; restore undoes the cut).")].join("\n");
|
|
793
|
+
}
|
|
794
|
+
/* fablecut_captions: caption clips from the transcripts (captions.js), subtitle files out and in. */
|
|
795
|
+
async function captionsTool(args) {
|
|
796
|
+
const C = require("./captions.js");
|
|
797
|
+
const st = C.style(args.style);
|
|
798
|
+
const ownLocks = (proj, c) => c.locked === true || (Array.isArray(proj.lockedTracks) && proj.lockedTracks.includes(c.track));
|
|
799
|
+
if (args.export != null) {
|
|
800
|
+
if (args.export !== "srt" && args.export !== "vtt") throw new Error("export must be srt or vtt");
|
|
801
|
+
const proj = readProject(), list = C.fromClips(proj.clips, proj.disabledTracks);
|
|
802
|
+
if (!list.length) throw new Error("there are no captions on the timeline to export — make them first (fablecut_captions {})");
|
|
803
|
+
fs.mkdirSync(EXPORTS_DIR, { recursive: true });
|
|
804
|
+
const base = String(proj.name || "captions").replace(/[^\w\- ]+/g, "_").trim().slice(0, 80) || "captions";
|
|
805
|
+
let file = path.join(EXPORTS_DIR, `${base}.${args.export}`);
|
|
806
|
+
for (let n = 2; fs.existsSync(file); n++) file = path.join(EXPORTS_DIR, `${base} ${n}.${args.export}`);
|
|
807
|
+
fs.writeFileSync(file, args.export === "srt" ? C.toSRT(list) : C.toVTT(list));
|
|
808
|
+
return `Wrote ${list.length} caption${list.length === 1 ? "" : "s"} to ${file} (${args.export === "srt" ? "SubRip" : "WebVTT"}, ${fmtClock(list[0].start)} → ${fmtClock(list[list.length - 1].end)}).`;
|
|
809
|
+
}
|
|
810
|
+
if (args.remove === true) {
|
|
811
|
+
const proj = readProject(), caps = proj.clips.filter(C.isCaption);
|
|
812
|
+
if (!caps.length) return "There are no captions on the timeline.";
|
|
813
|
+
const locked = caps.filter((c) => ownLocks(proj, c));
|
|
814
|
+
if (locked.length && args.force !== true) throw new Error(`${locked.length} caption(s) are locked — nothing removed (pass force:true only if the user asked)`);
|
|
815
|
+
ProjectOps.applyPatch(proj, caps.map((c) => ({ op: "removeClip", id: c.id, ...(args.force === true ? { force: true } : {}) })), { savedItems });
|
|
816
|
+
proj.revision = (proj.revision || 0) + 1;
|
|
817
|
+
writeProject(proj);
|
|
818
|
+
lastReadRevision = proj.revision;
|
|
819
|
+
return `Removed ${caps.length} caption${caps.length === 1 ? "" : "s"} (revision ${proj.revision}). UI hot-reloaded.`;
|
|
820
|
+
}
|
|
821
|
+
let list, note = "", sig;
|
|
822
|
+
const first = readProject();
|
|
823
|
+
const m = C.metrics(st, first.width || 1920, first.height || 1080, { lines: args.lines, words: args.words, scale: args.size });
|
|
824
|
+
if (args.import != null) {
|
|
825
|
+
let text = String(args.import);
|
|
826
|
+
const asFile = text.length < 1024 && !text.includes("-->");
|
|
827
|
+
if (asFile) {
|
|
828
|
+
const file = text.startsWith("/media/") ? path.join(MEDIA_DIR, decodeURIComponent(text.slice(7))) : path.resolve(text);
|
|
829
|
+
if (!fs.existsSync(file)) throw new Error("no such subtitle file: " + text);
|
|
830
|
+
text = fs.readFileSync(file, "utf8");
|
|
831
|
+
}
|
|
832
|
+
list = C.fit(C.parse(text), m.chars, m.lines);
|
|
833
|
+
sig = timelineSig(first);
|
|
834
|
+
note = `Read ${list.length} caption${list.length === 1 ? "" : "s"} from the ${/^WEBVTT/m.test(text) ? "WebVTT" : "SubRip"} file.\n`;
|
|
835
|
+
} else {
|
|
836
|
+
const r = await speechWords(args, false);
|
|
837
|
+
const lo = Number.isFinite(args.from) ? args.from : -Infinity, hi = Number.isFinite(args.to) ? args.to : Infinity;
|
|
838
|
+
const words = r.words.filter((w) => w.s >= lo && w.e <= hi);
|
|
839
|
+
if (!words.length) throw new Error("no words to caption" + (r.without.length ? ` — no transcript for ${r.without.join(", ")}` : " in that stretch"));
|
|
840
|
+
list = C.cues(words, { chars: m.chars, lines: m.lines, words: m.words, maxDur: m.maxDur, fps: r.doc.fps });
|
|
841
|
+
sig = r.sig;
|
|
842
|
+
note = r.note;
|
|
843
|
+
}
|
|
844
|
+
const proj = readProject(), readRev = proj.revision || 0;
|
|
845
|
+
if (timelineSig(proj) !== sig)
|
|
846
|
+
throw new Error("the timeline changed while transcribing (a clip was moved, trimmed or cut) — nothing added; run fablecut_captions again");
|
|
847
|
+
const old = args.replace === false ? [] : proj.clips.filter(C.isCaption);
|
|
848
|
+
const lockedOld = old.filter((c) => ownLocks(proj, c));
|
|
849
|
+
if (lockedOld.length && args.force !== true) throw new Error(`${lockedOld.length} existing caption(s) are locked — nothing changed (pass replace:false to keep them, or force:true if the user asked)`);
|
|
850
|
+
const from = list[0].start, to = list[list.length - 1].end;
|
|
851
|
+
let lane = args.track ? { track: String(args.track), add: false } : C.trackFor(old.length ? proj : { ...proj, clips: proj.clips.filter((c) => !C.isCaption(c)) }, from, to);
|
|
852
|
+
if (!/^V\d+$/.test(lane.track)) throw new Error("track must be a video lane such as V3");
|
|
853
|
+
if (args.track && !(proj.tracks || C.DEFAULT_TRACKS).some((t) => t.id === lane.track)) lane.add = true;
|
|
854
|
+
if (Array.isArray(proj.lockedTracks) && proj.lockedTracks.includes(lane.track) && args.force !== true) throw new Error(`${lane.track} is locked — pick another track, or unlock it`);
|
|
855
|
+
if (lane.add) proj.tracks = [{ id: lane.track, kind: "video" }, ...(Array.isArray(proj.tracks) && proj.tracks.length ? proj.tracks : C.DEFAULT_TRACKS)];
|
|
856
|
+
const ops = [
|
|
857
|
+
...old.map((c) => ({ op: "removeClip", id: c.id, ...(args.force === true ? { force: true } : {}) })),
|
|
858
|
+
...list.map((cue) => ({ op: "addClip", clip: C.clip(cue, { style: st, width: proj.width, height: proj.height, track: lane.track, scale: args.size }), ...(args.force === true ? { force: true } : {}) })),
|
|
859
|
+
];
|
|
860
|
+
ProjectOps.applyPatch(proj, ops, { savedItems });
|
|
861
|
+
proj.revision = readRev + 1;
|
|
862
|
+
writeProject(proj);
|
|
863
|
+
lastReadRevision = proj.revision;
|
|
864
|
+
const sample = list.slice(0, 3).map((c) => ` [${fmtClock(c.start)}] ${c.text.replace(/\n/g, " / ")}`);
|
|
865
|
+
return note + `Added ${list.length} caption${list.length === 1 ? "" : "s"} (${C.STYLES[st].label}, ${m.fontSize} px) on ${lane.track}${lane.add ? " (a new lane)" : ""}, ${fmtClock(from)} → ${fmtClock(to)}` +
|
|
866
|
+
(old.length ? `, replacing ${old.length}` : "") + ` (revision ${proj.revision}). UI hot-reloaded.\n` + sample.join("\n") +
|
|
867
|
+
(list.length > 3 ? `\n … ${list.length - 3} more` : "") + "\nfablecut_frame {time} shows how one looks; export:\"srt\" writes a subtitle file.";
|
|
509
868
|
}
|
|
510
869
|
/** The clips that sound for a selection: a linked group's audio stems, else the clip. */
|
|
511
870
|
function normalizeGroups(proj, ids) {
|
|
@@ -959,6 +1318,12 @@ async function callTool(name, args, attempt = 0) {
|
|
|
959
1318
|
return scopesTool(args);
|
|
960
1319
|
case "fablecut_frame":
|
|
961
1320
|
return frameTool(args);
|
|
1321
|
+
case "fablecut_silence":
|
|
1322
|
+
return silenceTool(args);
|
|
1323
|
+
case "fablecut_transcribe":
|
|
1324
|
+
return transcribeTool(args);
|
|
1325
|
+
case "fablecut_captions":
|
|
1326
|
+
return captionsTool(args);
|
|
962
1327
|
case "fablecut_denoise":
|
|
963
1328
|
return denoiseTool(args);
|
|
964
1329
|
case "fablecut_proxy":
|
|
@@ -1381,7 +1746,7 @@ async function handle(msg) {
|
|
|
1381
1746
|
result: {
|
|
1382
1747
|
protocolVersion: negotiateProtocolVersion(params?.protocolVersion),
|
|
1383
1748
|
capabilities: { tools: {} },
|
|
1384
|
-
serverInfo: { name: "fablecut", version: "1.
|
|
1749
|
+
serverInfo: { name: "fablecut", version: "1.17.0" },
|
|
1385
1750
|
},
|
|
1386
1751
|
});
|
|
1387
1752
|
}
|
package/package.json
CHANGED
package/project-ops.js
CHANGED
|
@@ -54,7 +54,7 @@
|
|
|
54
54
|
bold: true, weight: 0, italic: false, uppercase: false, align: "center",
|
|
55
55
|
letterSpacing: 0, lineHeight: 1.2, textShadow: 12, glow: 0, glowColor: "",
|
|
56
56
|
strokeWidth: 0, strokeColor: "#000", bgColor: "#000", bgOpacity: 0,
|
|
57
|
-
textAnim: "none", wordRate: 0.15, direction: "auto", boxW: 0, boxH: 0, boxFit: false, vAlign: "middle",
|
|
57
|
+
textAnim: "none", wordRate: 0.15, highlightColor: "#ffd166", direction: "auto", boxW: 0, boxH: 0, boxFit: false, vAlign: "middle",
|
|
58
58
|
anchorX: 0, anchorY: 0, trimStart: 0, trimEnd: 100, trimOffset: 0,
|
|
59
59
|
autoOrient: false, motionBlur: 0, motionBlurSamples: 8, pathOffset: 0, pathAlign: "start",
|
|
60
60
|
};
|
|
@@ -1169,14 +1169,15 @@
|
|
|
1169
1169
|
kept[k] = v;
|
|
1170
1170
|
continue;
|
|
1171
1171
|
}
|
|
1172
|
-
if (k === "masks" || k === "tracks" || k === "shapes" || k === "textPath") continue; // summarized below — point lists and samples are long
|
|
1172
|
+
if (k === "masks" || k === "tracks" || k === "shapes" || k === "textPath" || k === "wordTimes") continue; // summarized below — point lists and samples are long
|
|
1173
1173
|
if (hex(PROP_DEFAULTS[k]) !== hex(v)) kept[k] = v;
|
|
1174
1174
|
}
|
|
1175
1175
|
const masks = Mask.describe(Mask.normalizeMasks(o.masks)), tracks = Tracker.describe(Tracker.normalizeTracks(o.tracks));
|
|
1176
1176
|
const shapes = Motion.describe(Motion.normalizeShapes(o.shapes));
|
|
1177
1177
|
const tp = o.textPath && Motion.normalizeTextPath(o.textPath);
|
|
1178
1178
|
if (tp) kept.textPath = tp.type + (tp.points ? `(${tp.points.length})` : tp.w ? ` ${tp.w}×${tp.h}` : "");
|
|
1179
|
-
|
|
1179
|
+
const timed = Array.isArray(o.wordTimes) && o.wordTimes.length ? ` [${o.wordTimes.length} words timed to speech]` : "";
|
|
1180
|
+
return (Object.keys(kept).length ? " " + JSON.stringify(kept) : "") + (shapes ? ` [${shapes}]` : "") + (masks ? ` [${masks}]` : "") + (tracks ? ` [tracks: ${tracks}]` : "") + timed;
|
|
1180
1181
|
};
|
|
1181
1182
|
// Mixer: only off-default faders / pans, so a fresh project adds no line.
|
|
1182
1183
|
const signed = (v) => (v > 0 ? "+" : "") + v;
|
package/server.js
CHANGED
|
@@ -46,6 +46,7 @@ const Templates = require("./templates");
|
|
|
46
46
|
const { probeFile } = require("./media-probe");
|
|
47
47
|
const MediaLib = require("./media-lib");
|
|
48
48
|
const { createProxies } = require("./proxy");
|
|
49
|
+
const { createTranscripts } = require("./transcripts");
|
|
49
50
|
const Delivery = require("./delivery");
|
|
50
51
|
const { createProjects } = require("./projects");
|
|
51
52
|
const { createHistory } = require("./history");
|
|
@@ -124,6 +125,8 @@ function broadcast(event = "change", data = event) {
|
|
|
124
125
|
for (const res of sseClients) res.write(payload);
|
|
125
126
|
}
|
|
126
127
|
const proxies = createProxies({ dir: PROXIES_DIR, resolveSrc, probe: probeFile, broadcast: (ev, data) => broadcast(ev, data) });
|
|
128
|
+
/* Word transcripts, one per version of a file (fablecut_transcribe, the Transcript tab). */
|
|
129
|
+
const transcripts = createTranscripts({ dir: path.join(ANALYSIS_DIR, "transcripts"), resolveSrc });
|
|
127
130
|
let debounce = null;
|
|
128
131
|
let profilesDebounce = null;
|
|
129
132
|
function onFsChange() {
|
|
@@ -544,6 +547,8 @@ function stopExportSweep() {
|
|
|
544
547
|
headless browser the server starts (export-jobs.js). */
|
|
545
548
|
const exportJobs = createExportJobs({
|
|
546
549
|
url: (id) => `http://localhost:${PORT}/?exportJob=${encodeURIComponent(id)}`,
|
|
550
|
+
// a transcription's headless browser keeps its profile, so the speech model is downloaded once
|
|
551
|
+
keepProfile: (kind) => kind === "transcribe" ? path.join(ANALYSIS_DIR, "browser-profile") : null,
|
|
547
552
|
broadcast,
|
|
548
553
|
editors: () => sseClients.size,
|
|
549
554
|
});
|
|
@@ -786,6 +791,61 @@ const server = http.createServer(async (req, res) => {
|
|
|
786
791
|
return;
|
|
787
792
|
}
|
|
788
793
|
|
|
794
|
+
/* API: word transcripts (transcripts.js) — one per version of a file, times in file seconds.
|
|
795
|
+
GET /api/transcript?src= → {transcript} (null when there is none; 404 when the file is missing)
|
|
796
|
+
POST /api/transcript?src= {doc} → {src, words} — saved by the tab that transcribed it
|
|
797
|
+
POST /api/transcript/status {srcs} → {status:{src: {words, language, model, duration, created} | false | null}}
|
|
798
|
+
POST /api/transcript/delete {src} → {deleted}
|
|
799
|
+
Saves and deletes also arrive as SSE event "transcript" ({src}). */
|
|
800
|
+
if (p === "/api/transcript" && req.method === "GET") {
|
|
801
|
+
const src = url.searchParams.get("src") || "";
|
|
802
|
+
const d = transcripts.get(src);
|
|
803
|
+
if (d === null) { sendJSON(res, 404, { error: "no such file: " + src }); return; }
|
|
804
|
+
if (d === false) { sendJSON(res, 200, { transcript: null }); return; } // none yet: not an error
|
|
805
|
+
sendJSON(res, 200, { transcript: d });
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
if ((p === "/api/transcript" || p === "/api/transcript/status" || p === "/api/transcript/delete") && req.method === "POST") {
|
|
809
|
+
try {
|
|
810
|
+
const body = JSON.parse((await readBody(req)).toString("utf8") || "{}");
|
|
811
|
+
if (p === "/api/transcript") {
|
|
812
|
+
const src = url.searchParams.get("src") || body.src || "";
|
|
813
|
+
const d = transcripts.put(src, body);
|
|
814
|
+
broadcast("transcript", JSON.stringify({ src }));
|
|
815
|
+
sendJSON(res, 200, { src, words: d.words.length });
|
|
816
|
+
} else if (p === "/api/transcript/delete") {
|
|
817
|
+
const deleted = transcripts.remove(String(body.src || ""));
|
|
818
|
+
if (deleted) broadcast("transcript", JSON.stringify({ src: String(body.src) }));
|
|
819
|
+
sendJSON(res, 200, { deleted });
|
|
820
|
+
} else {
|
|
821
|
+
const status = {};
|
|
822
|
+
for (const src of (Array.isArray(body.srcs) ? body.srcs.slice(0, 2000).map(String) : [])) status[src] = transcripts.info(src);
|
|
823
|
+
sendJSON(res, 200, { status });
|
|
824
|
+
}
|
|
825
|
+
} catch (e) { sendJSON(res, e.code === 404 ? 404 : 400, { error: String(e.message || e) }); }
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
/* API: transcribe files (fablecut_transcribe) — a "transcribe" job on the
|
|
829
|
+
export-job queue; the tab that runs it saves each transcript. */
|
|
830
|
+
if (p === "/api/transcribe/request" && req.method === "POST") {
|
|
831
|
+
try {
|
|
832
|
+
const opts = JSON.parse((await readBody(req)).toString("utf8") || "{}");
|
|
833
|
+
const t = opts.transcribe;
|
|
834
|
+
if (!t || typeof t !== "object" || !Array.isArray(t.srcs) || !t.srcs.length || t.srcs.length > 200 || !t.srcs.every((x) => typeof x === "string")) {
|
|
835
|
+
sendJSON(res, 400, { error: "transcribe must be {srcs: [\"/media/…\", …] (1–200), model?, language?, again?}" }); return;
|
|
836
|
+
}
|
|
837
|
+
const missing = t.srcs.find((x) => !resolveSrc(x));
|
|
838
|
+
if (missing) { sendJSON(res, 404, { error: "no such file: " + missing }); return; }
|
|
839
|
+
const TR = require("./transcribe.js");
|
|
840
|
+
let spec;
|
|
841
|
+
try { spec = { srcs: [...new Set(t.srcs)], model: TR.model(t.model), language: TR.language(t.language), again: t.again === true }; }
|
|
842
|
+
catch (e) { sendJSON(res, 400, { error: e.message }); return; }
|
|
843
|
+
sendJSON(res, 200, exportJobs.request({ kind: "transcribe", where: opts.where, transcribe: spec }));
|
|
844
|
+
} catch (e) {
|
|
845
|
+
sendJSON(res, e.code === 409 || e.code === 400 ? e.code : 500, { error: String(e.message || e) });
|
|
846
|
+
}
|
|
847
|
+
return;
|
|
848
|
+
}
|
|
789
849
|
/* API: proxies (see proxy.js).
|
|
790
850
|
POST /api/proxy {srcs:[…], height?:540|720|1080} → {status:{src: status}} — queue them
|
|
791
851
|
POST /api/proxy/status {srcs:[…]} → {status:{src: status | null}}
|
package/silence.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/* FableCut silence — find the quiet stretches between phrases and cut them
|
|
2
|
+
out. Zero dependencies; loaded by the editor as a plain script (global
|
|
3
|
+
`FableCutSilence`) and required by the MCP server, so the inspector's
|
|
4
|
+
Silence section and `fablecut_silence` find the same spans and cut them
|
|
5
|
+
with the same `extract` ops.
|
|
6
|
+
|
|
7
|
+
Sound comes from ducking.js (rmsEnvelope → activeRegions → mergeRegions,
|
|
8
|
+
no gap bridging). Here: silentSpans (what lies between the sounds, inside
|
|
9
|
+
the clips, keeping `padding` of quiet around each phrase, on whole frames)
|
|
10
|
+
→ cutOps (one extract per span, last first, so earlier times stay put). */
|
|
11
|
+
(function (root, factory) {
|
|
12
|
+
const api = factory();
|
|
13
|
+
if (typeof module === "object" && module.exports) module.exports = api;
|
|
14
|
+
else root.FableCutSilence = api;
|
|
15
|
+
})(typeof self !== "undefined" ? self : this, function () {
|
|
16
|
+
"use strict";
|
|
17
|
+
|
|
18
|
+
const DEFAULTS = { threshold: -40, minSilence: 0.5, padding: 0.15 };
|
|
19
|
+
const LIMITS = { threshold: [-80, -10], minSilence: [0.1, 10], padding: [0, 2] };
|
|
20
|
+
/** Sound shorter than this still counts (a short word); quieter blips don't. */
|
|
21
|
+
const MIN_SOUND = 0.08;
|
|
22
|
+
/** edit-ops.js MIN_DUR: extract refuses a range this short or shorter. */
|
|
23
|
+
const MIN_CUT = 0.05;
|
|
24
|
+
|
|
25
|
+
/** The settings, defaulted and checked. Throws on a value out of range. */
|
|
26
|
+
function options(o = {}) {
|
|
27
|
+
const out = {};
|
|
28
|
+
for (const k of Object.keys(DEFAULTS)) {
|
|
29
|
+
const v = o[k] == null ? DEFAULTS[k] : +o[k];
|
|
30
|
+
const [lo, hi] = LIMITS[k];
|
|
31
|
+
if (!Number.isFinite(v) || v < lo || v > hi) throw new Error(`${k} must be ${lo}…${hi}`);
|
|
32
|
+
out[k] = v;
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Union of [start, end] spans, sorted. */
|
|
38
|
+
function union(list) {
|
|
39
|
+
const out = [];
|
|
40
|
+
for (const [s, e] of list.filter((r) => r[1] > r[0]).sort((x, y) => x[0] - y[0])) {
|
|
41
|
+
const last = out[out.length - 1];
|
|
42
|
+
if (last && s <= last[1] + 1e-6) last[1] = Math.max(last[1], e);
|
|
43
|
+
else out.push([s, e]);
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Silent spans to cut, timeline seconds: the gaps between `sound` regions
|
|
49
|
+
* inside `ranges` (the clips' extents) that last at least `minSilence`,
|
|
50
|
+
* less `padding` kept after the phrase before and before the phrase after
|
|
51
|
+
* (none at a range's own start or end), snapped inward to whole frames.
|
|
52
|
+
* Returns [{from, to}] in time order. */
|
|
53
|
+
function silentSpans(sound, ranges, { minSilence = DEFAULTS.minSilence, padding = DEFAULTS.padding, fps = 30 } = {}) {
|
|
54
|
+
const snd = union(sound);
|
|
55
|
+
const frame = 1 / Math.max(1, +fps || 30);
|
|
56
|
+
const out = [];
|
|
57
|
+
for (const [rs, re] of union(ranges)) {
|
|
58
|
+
let t = rs;
|
|
59
|
+
const gaps = [];
|
|
60
|
+
for (const [s, e] of snd) {
|
|
61
|
+
if (e <= rs || s >= re) continue;
|
|
62
|
+
if (s > t) gaps.push([t, s]);
|
|
63
|
+
t = Math.max(t, e);
|
|
64
|
+
}
|
|
65
|
+
if (t < re) gaps.push([t, re]);
|
|
66
|
+
for (const [a, b] of gaps) {
|
|
67
|
+
if (b - a < minSilence - 1e-9) continue;
|
|
68
|
+
const from = Math.ceil(((a > rs + 1e-6 ? a + padding : a) - 1e-6) / frame) * frame;
|
|
69
|
+
const to = Math.floor(((b < re - 1e-6 ? b - padding : b) + 1e-6) / frame) * frame;
|
|
70
|
+
// compared after rounding, against the strict minimum extract accepts (more than 0.05 s, at least a frame)
|
|
71
|
+
const span = { from: r4(from), to: r4(to) };
|
|
72
|
+
if (span.to - span.from > Math.max(frame - 1e-4, MIN_CUT)) out.push(span);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
const r4 = (x) => Math.round(x * 10000) / 10000 || 0; // as the editor stores times; never -0
|
|
78
|
+
|
|
79
|
+
/** Patch ops that cut the spans out, last first. `tracks` limits the lanes
|
|
80
|
+
* (default: the targeted tracks), `force` cuts through locked material. */
|
|
81
|
+
function cutOps(spans, { tracks = null, force = false } = {}) {
|
|
82
|
+
return spans.slice().sort((x, y) => y.from - x.from).map((s) => ({
|
|
83
|
+
op: "extract", from: s.from, to: s.to,
|
|
84
|
+
...(Array.isArray(tracks) && tracks.length ? { tracks: tracks.slice() } : {}),
|
|
85
|
+
...(force ? { force: true } : {}),
|
|
86
|
+
}));
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** A clip whose speed follows keyframes (a speed ramp): its sound can't be placed on the timeline
|
|
90
|
+
* from one speed, so it is left out of silence detection rather than risk cutting speech. */
|
|
91
|
+
const ramped = (c) => !!(c && c.keyframes && Array.isArray(c.keyframes.speed) && c.keyframes.speed.length);
|
|
92
|
+
|
|
93
|
+
/** Seconds the spans add up to. */
|
|
94
|
+
const total = (spans) => r4(spans.reduce((n, s) => n + (s.to - s.from), 0));
|
|
95
|
+
|
|
96
|
+
return { DEFAULTS, LIMITS, MIN_SOUND, options, union, silentSpans, cutOps, total, ramped };
|
|
97
|
+
});
|