fablecut 1.15.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/server.js CHANGED
@@ -46,7 +46,10 @@ 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");
51
+ const { createProjects } = require("./projects");
52
+ const { createHistory } = require("./history");
50
53
 
51
54
  /* Static app files are served from the install dir; everything the user creates
52
55
  lives under DATA_DIR. The two are the same unless FABLECUT_DATA_DIR is set. */
@@ -96,6 +99,18 @@ const MIME = {
96
99
  };
97
100
 
98
101
  ensureDirs();
102
+ const projects = createProjects({ dataDir: DATA_DIR, projectFile: PROJECT_FILE, libraryDir: LIBRARY_DIR });
103
+ const history = createHistory({ projects, autoMinutes: Number(process.env.FABLECUT_AUTO_VERSION_MIN) || 10 });
104
+ /* project.json that can't be read at startup (a crash mid-write by another tool, a
105
+ bad hand edit): keep it aside and put back the newest good copy. */
106
+ if (fs.existsSync(PROJECT_FILE)) {
107
+ try { JSON.parse(fs.readFileSync(PROJECT_FILE, "utf8").replace(/^/, "")); }
108
+ catch (e) {
109
+ const r = history.recover(PROJECT_FILE);
110
+ console.warn(` ⚠ project.json could not be read (${e.message}); kept as ${path.basename(r.aside)}` +
111
+ (r.recovered ? ` and restored from ${r.from}` : " — starting a new project"));
112
+ }
113
+ }
99
114
  if (!fs.existsSync(PROJECT_FILE)) {
100
115
  fs.writeFileSync(PROJECT_FILE, JSON.stringify({
101
116
  name: "Untitled Project", width: 1280, height: 720, fps: 30,
@@ -110,6 +125,8 @@ function broadcast(event = "change", data = event) {
110
125
  for (const res of sseClients) res.write(payload);
111
126
  }
112
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 });
113
130
  let debounce = null;
114
131
  let profilesDebounce = null;
115
132
  function onFsChange() {
@@ -530,6 +547,8 @@ function stopExportSweep() {
530
547
  headless browser the server starts (export-jobs.js). */
531
548
  const exportJobs = createExportJobs({
532
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,
533
552
  broadcast,
534
553
  editors: () => sseClients.size,
535
554
  });
@@ -581,10 +600,96 @@ const server = http.createServer(async (req, res) => {
581
600
  /* API: project */
582
601
  if (p === "/api/project" && req.method === "GET") {
583
602
  // strip UTF-8 BOM some editors/PowerShell prepend, which breaks JSON.parse
584
- try { sendJSON(res, 200, JSON.parse(fs.readFileSync(PROJECT_FILE, "utf8").replace(new RegExp("^\\uFEFF"), ""))); }
603
+ try {
604
+ const doc = JSON.parse(fs.readFileSync(PROJECT_FILE, "utf8").replace(new RegExp("^\\uFEFF"), ""));
605
+ // which project this is, once there are several: the editor resets undo when it changes
606
+ const id = projects.peekActive();
607
+ res.setHeader("X-FableCut-Projects", "1");
608
+ if (id) res.setHeader("X-FableCut-Project", id);
609
+ sendJSON(res, 200, doc);
610
+ }
585
611
  catch (e) { sendJSON(res, 500, { error: String(e) }); }
586
612
  return;
587
613
  }
614
+
615
+ /* API: projects — the dashboard. GET lists them (?archived=only|all) with the
616
+ project templates; POST {action, …} creates, opens, duplicates, renames,
617
+ archives, deletes, imports, and saves / deletes templates (projects.js).
618
+ GET / PUT /api/projects/thumb?id= is a project's JPEG thumbnail. */
619
+ if (p === "/api/projects" && req.method === "GET") {
620
+ try {
621
+ const archived = ["only", "all"].includes(url.searchParams.get("archived")) ? url.searchParams.get("archived") : "exclude";
622
+ sendJSON(res, 200, projects.act({ action: "list", archived }));
623
+ } catch (e) { sendJSON(res, 500, { error: e.message }); }
624
+ return;
625
+ }
626
+ if (p === "/api/projects" && req.method === "POST") {
627
+ let a;
628
+ try { a = JSON.parse((await readBody(req)).toString("utf8") || "{}"); }
629
+ catch { sendJSON(res, 400, { error: "body must be JSON {action, …}" }); return; }
630
+ try {
631
+ // a backup file (a project with its versions) imports through history.js
632
+ const out = a.action === "import" && a.project?.fablecut === "backup" ? history.importBackup(a.project, a) : projects.act(a);
633
+ broadcast("projects", JSON.stringify({ action: a.action, id: out.id || a.id || null, active: projects.activeId() }));
634
+ // opening, or renaming the open project, rewrites ./project.json: reload the tabs now, watcher or not
635
+ if (out.from || ((a.action === "update" || a.action === "rename") && out.project?.active)) onFsChange();
636
+ sendJSON(res, 200, out);
637
+ } catch (e) { sendJSON(res, /^no (project|saved template)/.test(e.message) ? 404 : 400, { error: e.message }); }
638
+ return;
639
+ }
640
+ /* API: versions (history.js) — GET ?project= lists them (default: the open project);
641
+ POST {action, project?, version?, …} saves, restores, compares, renames / marks
642
+ final, deletes; GET /api/versions/file?project=&version= is one version's document.
643
+ GET /api/projects/backup?id= is a project with all its versions, as one file. */
644
+ if (p === "/api/versions" && req.method === "GET") {
645
+ try { sendJSON(res, 200, history.list(url.searchParams.get("project") || null)); }
646
+ catch (e) { sendJSON(res, /^no project/.test(e.message) ? 404 : 400, { error: e.message }); }
647
+ return;
648
+ }
649
+ if (p === "/api/versions" && req.method === "POST") {
650
+ let a;
651
+ try { a = JSON.parse((await readBody(req)).toString("utf8") || "{}"); }
652
+ catch { sendJSON(res, 400, { error: "body must be JSON {action, …}" }); return; }
653
+ try {
654
+ const out = history.act(a);
655
+ if (a.action && a.action !== "list" && a.action !== "diff") broadcast("versions", JSON.stringify({ project: out.project, action: a.action }));
656
+ const isOpen = out.project === projects.peekActive();
657
+ if (a.action === "restore" && isOpen) onFsChange(); // the tabs load the restored document
658
+ sendJSON(res, 200, a.action === "restore" ? { ...out, open: isOpen } : out);
659
+ } catch (e) { sendJSON(res, /^no (project|version)/.test(e.message) ? 404 : 400, { error: e.message }); }
660
+ return;
661
+ }
662
+ if (p === "/api/versions/file" && req.method === "GET") {
663
+ try {
664
+ const doc = history.get(url.searchParams.get("project") || null, url.searchParams.get("version"));
665
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store",
666
+ "Content-Disposition": `attachment; filename="${safeName(doc.name || "project")}-v${String(url.searchParams.get("version")).replace(/\D/g, "")}.json"` });
667
+ res.end(JSON.stringify(doc, null, 2));
668
+ } catch (e) { sendJSON(res, /^no (project|version)/.test(e.message) ? 404 : 400, { error: e.message }); }
669
+ return;
670
+ }
671
+ if (p === "/api/projects/backup" && req.method === "GET") {
672
+ try {
673
+ const b = history.backup(url.searchParams.get("id") || null);
674
+ res.writeHead(200, { "Content-Type": "application/json", "Cache-Control": "no-store",
675
+ "Content-Disposition": `attachment; filename="${safeName(b.name || "project")}.fablecut-backup.json"` });
676
+ res.end(JSON.stringify(b));
677
+ } catch (e) { sendJSON(res, /^no project/.test(e.message) ? 404 : 400, { error: e.message }); }
678
+ return;
679
+ }
680
+ if (p === "/api/projects/thumb" && (req.method === "GET" || req.method === "PUT")) {
681
+ const id = url.searchParams.get("id") || "";
682
+ if (req.method === "GET") {
683
+ const file = projects.thumbPath(id);
684
+ if (!file) { res.writeHead(404); res.end(); return; }
685
+ res.writeHead(200, { "Content-Type": "image/jpeg", "Cache-Control": "no-store" });
686
+ fs.createReadStream(file).pipe(res);
687
+ return;
688
+ }
689
+ try { sendJSON(res, 200, projects.setThumb(id, await readBody(req))); }
690
+ catch (e) { sendJSON(res, /^no project/.test(e.message) ? 404 : 400, { error: e.message }); }
691
+ return;
692
+ }
588
693
  if (p === "/api/project" && req.method === "PUT") {
589
694
  try {
590
695
  const body = await readBody(req);
@@ -595,6 +700,12 @@ const server = http.createServer(async (req, res) => {
595
700
  ?force=1 skips the check for deliberate overwrites. */
596
701
  let cur = {};
597
702
  try { cur = JSON.parse(fs.readFileSync(PROJECT_FILE, "utf8").replace(new RegExp("^\\uFEFF"), "")); } catch {}
703
+ // a save the editor made for another project (it sends the id it loaded) never lands here
704
+ const meant = req.headers["x-fablecut-project"], open = projects.peekActive();
705
+ if (meant && open && meant !== open) {
706
+ sendJSON(res, 409, { error: "another project is open now", revision: cur.revision || 0, project: open });
707
+ return;
708
+ }
598
709
  if ((data.revision || 0) <= (cur.revision || 0) && url.searchParams.get("force") !== "1") {
599
710
  sendJSON(res, 409, { error: "stale revision — project changed since it was read", revision: cur.revision || 0 });
600
711
  return;
@@ -680,6 +791,61 @@ const server = http.createServer(async (req, res) => {
680
791
  return;
681
792
  }
682
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
+ }
683
849
  /* API: proxies (see proxy.js).
684
850
  POST /api/proxy {srcs:[…], height?:540|720|1080} → {status:{src: status}} — queue them
685
851
  POST /api/proxy/status {srcs:[…]} → {status:{src: status | null}}
@@ -1268,6 +1434,15 @@ const server = http.createServer(async (req, res) => {
1268
1434
  serveFile(req, res, file);
1269
1435
  });
1270
1436
 
1437
+ /* Auto-save versions of the open project while it changes (every FABLECUT_AUTO_VERSION_MIN
1438
+ minutes at most, default 10), whoever edits it: the editor, an agent, a script. */
1439
+ setInterval(() => {
1440
+ try {
1441
+ const v = history.maybeAuto();
1442
+ if (v) broadcast("versions", JSON.stringify({ project: projects.peekActive(), action: "auto" }));
1443
+ } catch { }
1444
+ }, 60_000).unref();
1445
+
1271
1446
  server.listen(PORT, HOST, () => {
1272
1447
  console.log(`\n FableCut running → http://localhost:${PORT}\n`);
1273
1448
  if (!["127.0.0.1", "localhost", "::1"].includes(HOST))
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
+ });