@lumy-pack/scene-sieve 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,936 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ extractScenes: () => runPipeline
34
+ });
35
+ module.exports = __toCommonJS(src_exports);
36
+
37
+ // ../../node_modules/tsup/assets/cjs_shims.js
38
+ var getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ var importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
40
+
41
+ // src/core/orchestrator.ts
42
+ var import_node_crypto = require("crypto");
43
+
44
+ // src/utils/logger.ts
45
+ var import_picocolors = __toESM(require("picocolors"), 1);
46
+ var debugMode = false;
47
+ function setDebugMode(enabled) {
48
+ debugMode = enabled;
49
+ }
50
+ function timestamp() {
51
+ return (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
52
+ }
53
+ var logger = {
54
+ info(message) {
55
+ console.log(`${import_picocolors.default.blue("info")} ${message}`);
56
+ },
57
+ success(message) {
58
+ console.log(`${import_picocolors.default.green("done")} ${message}`);
59
+ },
60
+ warn(message) {
61
+ console.warn(`${import_picocolors.default.yellow("warn")} ${message}`);
62
+ },
63
+ error(message) {
64
+ console.error(`${import_picocolors.default.red("error")} ${message}`);
65
+ },
66
+ debug(message) {
67
+ if (debugMode) {
68
+ console.log(`${import_picocolors.default.gray(`[${timestamp()}] debug`)} ${message}`);
69
+ }
70
+ }
71
+ };
72
+
73
+ // src/core/analyzer.ts
74
+ var import_node_module = require("module");
75
+ var import_sharp = __toESM(require("sharp"), 1);
76
+
77
+ // src/constants.ts
78
+ var import_node_os = require("os");
79
+ var import_node_path = require("path");
80
+ var APP_NAME = "scene-sieve";
81
+ var DEFAULT_COUNT = 5;
82
+ var DEFAULT_FPS = 5;
83
+ var DEFAULT_SCALE = 720;
84
+ var DEFAULT_QUALITY = 80;
85
+ var WORKSPACE_PREFIX = `${APP_NAME}-`;
86
+ var TEMP_BASE_DIR = (0, import_node_os.tmpdir)();
87
+ var SUPPORTED_VIDEO_EXTENSIONS = [
88
+ ".mp4",
89
+ ".mov",
90
+ ".avi",
91
+ ".mkv",
92
+ ".webm"
93
+ ];
94
+ var SUPPORTED_GIF_EXTENSIONS = [".gif"];
95
+ var FRAME_OUTPUT_EXTENSION = ".jpg";
96
+ var OPENCV_BATCH_SIZE = 10;
97
+ var MIN_IFRAME_COUNT = 3;
98
+ var DBSCAN_ALPHA = 0.03;
99
+ var DBSCAN_MIN_PTS = 4;
100
+ var IOU_THRESHOLD = 0.9;
101
+ var DECAY_LAMBDA = 0.95;
102
+ var ANIMATION_FRAME_THRESHOLD = 5;
103
+ var MATCH_DISTANCE_THRESHOLD = 0.75;
104
+ function getTempWorkspaceDir(sessionId) {
105
+ return (0, import_node_path.join)(TEMP_BASE_DIR, `${WORKSPACE_PREFIX}${sessionId}`);
106
+ }
107
+
108
+ // src/core/dbscan.ts
109
+ var UNVISITED = -2;
110
+ var NOISE = -1;
111
+ function dbscan(points, imageWidth, imageHeight, alpha, minPts) {
112
+ if (points.length === 0) {
113
+ return { labels: [], boundingBoxes: [] };
114
+ }
115
+ const eps = (alpha ?? DBSCAN_ALPHA) * Math.sqrt(imageWidth ** 2 + imageHeight ** 2);
116
+ const epsSquared = eps * eps;
117
+ const minPoints = minPts ?? DBSCAN_MIN_PTS;
118
+ const labels = new Array(points.length).fill(UNVISITED);
119
+ let clusterId = 0;
120
+ for (let i = 0; i < points.length; i++) {
121
+ if (labels[i] !== UNVISITED) continue;
122
+ const neighbors = findNeighbors(points, i, epsSquared);
123
+ if (neighbors.length < minPoints) {
124
+ labels[i] = NOISE;
125
+ continue;
126
+ }
127
+ labels[i] = clusterId;
128
+ const seeds = [...neighbors];
129
+ const seedSet = new Set(seeds);
130
+ for (let si = 0; si < seeds.length; si++) {
131
+ const q = seeds[si];
132
+ if (labels[q] === NOISE) {
133
+ labels[q] = clusterId;
134
+ }
135
+ if (labels[q] !== UNVISITED) continue;
136
+ labels[q] = clusterId;
137
+ const qNeighbors = findNeighbors(points, q, epsSquared);
138
+ if (qNeighbors.length >= minPoints) {
139
+ for (const n of qNeighbors) {
140
+ if (!seedSet.has(n)) {
141
+ seedSet.add(n);
142
+ seeds.push(n);
143
+ }
144
+ }
145
+ }
146
+ }
147
+ clusterId++;
148
+ }
149
+ const boundingBoxes = [];
150
+ for (let c = 0; c < clusterId; c++) {
151
+ let minX = Infinity;
152
+ let minY = Infinity;
153
+ let maxX = -Infinity;
154
+ let maxY = -Infinity;
155
+ for (let i = 0; i < points.length; i++) {
156
+ if (labels[i] !== c) continue;
157
+ const p = points[i];
158
+ if (p.x < minX) minX = p.x;
159
+ if (p.y < minY) minY = p.y;
160
+ if (p.x > maxX) maxX = p.x;
161
+ if (p.y > maxY) maxY = p.y;
162
+ }
163
+ boundingBoxes.push({
164
+ x: minX,
165
+ y: minY,
166
+ width: maxX - minX,
167
+ height: maxY - minY
168
+ });
169
+ }
170
+ return { labels, boundingBoxes };
171
+ }
172
+ function findNeighbors(points, idx, epsSquared) {
173
+ const p = points[idx];
174
+ const neighbors = [];
175
+ for (let i = 0; i < points.length; i++) {
176
+ if (i === idx) continue;
177
+ const q = points[i];
178
+ const distSq = (p.x - q.x) ** 2 + (p.y - q.y) ** 2;
179
+ if (distSq <= epsSquared) {
180
+ neighbors.push(i);
181
+ }
182
+ }
183
+ return neighbors;
184
+ }
185
+
186
+ // src/core/analyzer.ts
187
+ var OPENCV_INIT_TIMEOUT_MS = 3e4;
188
+ var require2 = (0, import_node_module.createRequire)(importMetaUrl);
189
+ var cvReady = null;
190
+ async function ensureOpenCV() {
191
+ if (!cvReady) {
192
+ cvReady = (async () => {
193
+ const cvObj = require2("@techstark/opencv-js");
194
+ delete cvObj.then;
195
+ if (cvObj.Mat) return cvObj;
196
+ return new Promise((resolve2, reject) => {
197
+ const timeout = setTimeout(() => {
198
+ reject(new Error("OpenCV WASM initialization timed out after 30s"));
199
+ }, OPENCV_INIT_TIMEOUT_MS);
200
+ cvObj.onRuntimeInitialized = () => {
201
+ clearTimeout(timeout);
202
+ resolve2(cvObj);
203
+ };
204
+ });
205
+ })();
206
+ }
207
+ return cvReady;
208
+ }
209
+ async function preprocessFrame(framePath, scale) {
210
+ const { data, info } = await (0, import_sharp.default)(framePath).resize({ width: scale, withoutEnlargement: true }).grayscale().blur(1).raw().toBuffer({ resolveWithObject: true });
211
+ return {
212
+ data: new Uint8Array(data.buffer),
213
+ width: info.width,
214
+ height: info.height
215
+ };
216
+ }
217
+ function computeIoU(a, b) {
218
+ const ix1 = Math.max(a.x, b.x);
219
+ const iy1 = Math.max(a.y, b.y);
220
+ const ix2 = Math.min(a.x + a.width, b.x + b.width);
221
+ const iy2 = Math.min(a.y + a.height, b.y + b.height);
222
+ const iw = Math.max(0, ix2 - ix1);
223
+ const ih = Math.max(0, iy2 - iy1);
224
+ const intersection = iw * ih;
225
+ if (intersection === 0) return 0;
226
+ const aArea = a.width * a.height;
227
+ const bArea = b.width * b.height;
228
+ const union = aArea + bArea - intersection;
229
+ return union === 0 ? 0 : intersection / union;
230
+ }
231
+ var IoUTracker = class {
232
+ regions = [];
233
+ update(boxes, pairIndex) {
234
+ const animationIndices = /* @__PURE__ */ new Set();
235
+ const matched = /* @__PURE__ */ new Set();
236
+ for (let bi = 0; bi < boxes.length; bi++) {
237
+ const box = boxes[bi];
238
+ let bestIoU = 0;
239
+ let bestRegionIdx = -1;
240
+ for (let ri = 0; ri < this.regions.length; ri++) {
241
+ if (matched.has(ri)) continue;
242
+ const iou = computeIoU(box, this.regions[ri].box);
243
+ if (iou > bestIoU) {
244
+ bestIoU = iou;
245
+ bestRegionIdx = ri;
246
+ }
247
+ }
248
+ if (bestIoU > IOU_THRESHOLD && bestRegionIdx !== -1) {
249
+ const region = this.regions[bestRegionIdx];
250
+ const gap = pairIndex - region.lastSeen;
251
+ region.box = box;
252
+ region.consecutiveCount++;
253
+ region.lastSeen = pairIndex;
254
+ region.weight *= Math.pow(DECAY_LAMBDA, gap);
255
+ matched.add(bestRegionIdx);
256
+ if (region.consecutiveCount >= ANIMATION_FRAME_THRESHOLD) {
257
+ animationIndices.add(bi);
258
+ }
259
+ } else {
260
+ this.regions.push({
261
+ box,
262
+ consecutiveCount: 1,
263
+ lastSeen: pairIndex,
264
+ weight: 1
265
+ });
266
+ }
267
+ }
268
+ for (let ri = 0; ri < this.regions.length; ri++) {
269
+ if (!matched.has(ri)) {
270
+ const gap = pairIndex - this.regions[ri].lastSeen;
271
+ this.regions[ri].weight *= Math.pow(DECAY_LAMBDA, gap);
272
+ }
273
+ }
274
+ this.regions = this.regions.filter((r) => r.weight > 0.01);
275
+ return animationIndices;
276
+ }
277
+ getAnimationWeight(boxIndex, boxes) {
278
+ if (boxIndex >= boxes.length) return 0;
279
+ const box = boxes[boxIndex];
280
+ let maxWeight = 0;
281
+ for (const region of this.regions) {
282
+ if (region.consecutiveCount >= ANIMATION_FRAME_THRESHOLD) {
283
+ const iou = computeIoU(box, region.box);
284
+ if (iou > IOU_THRESHOLD) {
285
+ maxWeight = Math.max(maxWeight, region.weight);
286
+ }
287
+ }
288
+ }
289
+ return maxWeight;
290
+ }
291
+ };
292
+ async function computeAKAZEDiff(cvLib, frame1, frame2) {
293
+ const mat1 = cvLib.matFromImageData({
294
+ data: frame1.data,
295
+ width: frame1.width,
296
+ height: frame1.height
297
+ });
298
+ const mat2 = cvLib.matFromImageData({
299
+ data: frame2.data,
300
+ width: frame2.width,
301
+ height: frame2.height
302
+ });
303
+ const kp1 = new cvLib.KeyPointVector();
304
+ const kp2 = new cvLib.KeyPointVector();
305
+ const desc1 = new cvLib.Mat();
306
+ const desc2 = new cvLib.Mat();
307
+ const mask1 = new cvLib.Mat();
308
+ const mask2 = new cvLib.Mat();
309
+ const akaze = new cvLib.AKAZE();
310
+ let matches = null;
311
+ try {
312
+ akaze.detectAndCompute(mat1, mask1, kp1, desc1);
313
+ akaze.detectAndCompute(mat2, mask2, kp2, desc2);
314
+ const matchedKp1Indices = /* @__PURE__ */ new Set();
315
+ const matchedKp2Indices = /* @__PURE__ */ new Set();
316
+ if (desc1.rows > 0 && desc2.rows > 0) {
317
+ const matcher = new cvLib.BFMatcher(cvLib.NORM_HAMMING, false);
318
+ try {
319
+ matches = new cvLib.DMatchVectorVector();
320
+ matcher.knnMatch(desc1, desc2, matches, 2);
321
+ for (let i = 0; i < matches.size(); i++) {
322
+ const pair = matches.get(i);
323
+ if (pair.size() < 2) continue;
324
+ const m0 = pair.get(0);
325
+ const m1 = pair.get(1);
326
+ if (m0.distance < MATCH_DISTANCE_THRESHOLD * m1.distance) {
327
+ matchedKp1Indices.add(m0.queryIdx);
328
+ matchedKp2Indices.add(m0.trainIdx);
329
+ }
330
+ }
331
+ } finally {
332
+ matcher.delete();
333
+ }
334
+ }
335
+ const sNew = [];
336
+ for (let i = 0; i < kp2.size(); i++) {
337
+ if (!matchedKp2Indices.has(i)) {
338
+ const pt = kp2.get(i).pt;
339
+ sNew.push({ x: pt.x, y: pt.y });
340
+ }
341
+ }
342
+ const sLoss = [];
343
+ for (let i = 0; i < kp1.size(); i++) {
344
+ if (!matchedKp1Indices.has(i)) {
345
+ const pt = kp1.get(i).pt;
346
+ sLoss.push({ x: pt.x, y: pt.y });
347
+ }
348
+ }
349
+ return { sNew, sLoss };
350
+ } finally {
351
+ mat1.delete();
352
+ mat2.delete();
353
+ kp1.delete();
354
+ kp2.delete();
355
+ desc1.delete();
356
+ desc2.delete();
357
+ mask1.delete();
358
+ mask2.delete();
359
+ akaze.delete();
360
+ if (matches) matches.delete();
361
+ }
362
+ }
363
+ function computeInformationGain(clusters, clusterPoints, imageArea, animationIndices, animationWeights) {
364
+ if (clusters.length === 0) return 0;
365
+ let gain = 0;
366
+ for (let i = 0; i < clusters.length; i++) {
367
+ const box = clusters[i];
368
+ const clusterArea = box.width * box.height;
369
+ if (clusterArea <= 0) continue;
370
+ const normalizedArea = clusterArea / imageArea;
371
+ const featureDensity = clusterPoints[i] / clusterArea;
372
+ let contribution = normalizedArea * featureDensity;
373
+ if (animationIndices.has(i)) {
374
+ const animWeight = animationWeights[i] ?? 0;
375
+ contribution *= 1 - animWeight;
376
+ }
377
+ gain += contribution;
378
+ }
379
+ return gain;
380
+ }
381
+ async function analyzeBatch(cvLib, frames, scale, tracker, pairOffset) {
382
+ const edges = [];
383
+ const preprocessed = await Promise.all(
384
+ frames.map((f) => preprocessFrame(f.extractPath, scale))
385
+ );
386
+ const imageWidth = preprocessed[0]?.width ?? scale;
387
+ const imageHeight = preprocessed[0]?.height ?? Math.round(scale * 9 / 16);
388
+ const imageArea = imageWidth * imageHeight;
389
+ for (let i = 0; i < frames.length - 1; i++) {
390
+ const pairIndex = pairOffset + i;
391
+ try {
392
+ const { sNew } = await computeAKAZEDiff(
393
+ cvLib,
394
+ preprocessed[i],
395
+ preprocessed[i + 1]
396
+ );
397
+ const dbscanResult = dbscan(sNew, imageWidth, imageHeight);
398
+ const clusters = dbscanResult.boundingBoxes;
399
+ const clusterPointCounts = new Array(clusters.length).fill(0);
400
+ for (const label of dbscanResult.labels) {
401
+ if (label >= 0) {
402
+ clusterPointCounts[label]++;
403
+ }
404
+ }
405
+ const animationIndices = tracker.update(clusters, pairIndex);
406
+ const animationWeights = clusters.map(
407
+ (_, ci) => animationIndices.has(ci) ? tracker.getAnimationWeight(ci, clusters) : 0
408
+ );
409
+ const score = computeInformationGain(
410
+ clusters,
411
+ clusterPointCounts,
412
+ imageArea,
413
+ animationIndices,
414
+ animationWeights
415
+ );
416
+ logger.debug(`Edge ${frames[i].id}->${frames[i + 1].id} G(t)=${score.toFixed(6)}`);
417
+ edges.push({
418
+ sourceId: frames[i].id,
419
+ targetId: frames[i + 1].id,
420
+ score
421
+ });
422
+ } catch (err) {
423
+ logger.debug(`Frame pair analysis failed: ${String(err)}`);
424
+ edges.push({
425
+ sourceId: frames[i].id,
426
+ targetId: frames[i + 1].id,
427
+ score: 0
428
+ });
429
+ }
430
+ }
431
+ return edges;
432
+ }
433
+ async function analyzeFrames(ctx) {
434
+ const { frames } = ctx;
435
+ if (frames.length < 2) return [];
436
+ logger.debug(
437
+ `Analyzing ${frames.length} frames in batches of ${OPENCV_BATCH_SIZE}`
438
+ );
439
+ const cvLib = await ensureOpenCV();
440
+ const edges = [];
441
+ const tracker = new IoUTracker();
442
+ const scale = ctx.options.scale;
443
+ for (let i = 0; i < frames.length - 1; i += OPENCV_BATCH_SIZE) {
444
+ const batchEnd = Math.min(i + OPENCV_BATCH_SIZE + 1, frames.length);
445
+ const batch = frames.slice(i, batchEnd);
446
+ const batchEdges = await analyzeBatch(cvLib, batch, scale, tracker, i);
447
+ edges.push(...batchEdges);
448
+ const progress = Math.min(
449
+ 100,
450
+ (i + OPENCV_BATCH_SIZE) / (frames.length - 1) * 100
451
+ );
452
+ ctx.emitProgress(progress);
453
+ }
454
+ logger.debug(`Computed ${edges.length} score edges`);
455
+ return edges;
456
+ }
457
+
458
+ // src/core/extractor.ts
459
+ var import_promises2 = require("fs/promises");
460
+ var import_node_path3 = require("path");
461
+ var import_fluent_ffmpeg = __toESM(require("fluent-ffmpeg"), 1);
462
+ var import_ffmpeg_static = __toESM(require("ffmpeg-static"), 1);
463
+ var import_ffprobe = require("@ffprobe-installer/ffprobe");
464
+
465
+ // src/utils/paths.ts
466
+ var import_promises = require("fs/promises");
467
+ var import_node_path2 = require("path");
468
+ async function ensureDir(dirPath) {
469
+ await (0, import_promises.mkdir)(dirPath, { recursive: true });
470
+ }
471
+ async function fileExists(filePath) {
472
+ try {
473
+ await (0, import_promises.stat)(filePath);
474
+ return true;
475
+ } catch {
476
+ return false;
477
+ }
478
+ }
479
+ function deriveOutputPath(inputPath) {
480
+ const dir = (0, import_node_path2.resolve)(inputPath, "..");
481
+ const name = (0, import_node_path2.basename)(inputPath, (0, import_node_path2.extname)(inputPath));
482
+ return (0, import_node_path2.resolve)(dir, `${name}_scenes`);
483
+ }
484
+ function isSupportedFile(filePath, extensions) {
485
+ return extensions.includes((0, import_node_path2.extname)(filePath).toLowerCase());
486
+ }
487
+
488
+ // src/core/extractor.ts
489
+ if (import_ffmpeg_static.default) import_fluent_ffmpeg.default.setFfmpegPath(import_ffmpeg_static.default);
490
+ import_fluent_ffmpeg.default.setFfprobePath(import_ffprobe.path);
491
+ async function extractFrames(ctx) {
492
+ const framesDir = (0, import_node_path3.join)(ctx.workspacePath, "frames");
493
+ const { inputPath, fps, scale } = ctx.options;
494
+ if (!inputPath) {
495
+ throw new Error("inputPath is required for frame extraction");
496
+ }
497
+ const exists = await fileExists(inputPath);
498
+ if (!exists) {
499
+ throw new Error(`Input file not found: ${inputPath}`);
500
+ }
501
+ const allExtensions = [...SUPPORTED_VIDEO_EXTENSIONS, ...SUPPORTED_GIF_EXTENSIONS];
502
+ if (!isSupportedFile(inputPath, allExtensions)) {
503
+ throw new Error(`Unsupported file format: ${inputPath}`);
504
+ }
505
+ logger.debug(`Extracting frames from: ${inputPath}`);
506
+ await ensureDir(framesDir);
507
+ const isGif = isSupportedFile(inputPath, SUPPORTED_GIF_EXTENSIONS);
508
+ let frames;
509
+ if (isGif) {
510
+ logger.debug("GIF detected \u2014 using FPS extraction");
511
+ frames = await extractByFps(inputPath, framesDir, fps, scale);
512
+ } else {
513
+ frames = await extractIFrames(inputPath, framesDir, scale);
514
+ if (frames.length < MIN_IFRAME_COUNT) {
515
+ logger.debug(
516
+ `Insufficient I-frames (${frames.length}), falling back to FPS mode`
517
+ );
518
+ frames = await extractByFps(inputPath, framesDir, fps, scale);
519
+ }
520
+ }
521
+ ctx.emitProgress(100);
522
+ logger.debug(`Extracted ${frames.length} frames`);
523
+ return frames;
524
+ }
525
+ async function extractIFrames(inputPath, outputDir, scale) {
526
+ const outputPattern = (0, import_node_path3.join)(outputDir, "frame_%06d.jpg");
527
+ await new Promise((resolve2, reject) => {
528
+ (0, import_fluent_ffmpeg.default)(inputPath).outputOptions([
529
+ `-vf select='eq(pict_type,I)',scale=-1:${scale}`,
530
+ "-vsync vfr",
531
+ "-q:v 2"
532
+ ]).output(outputPattern).on("end", () => resolve2()).on("error", (err) => reject(err)).run();
533
+ });
534
+ return buildFrameList(outputDir, inputPath);
535
+ }
536
+ async function extractByFps(inputPath, outputDir, fps, scale) {
537
+ const outputPattern = (0, import_node_path3.join)(outputDir, "frame_%06d.jpg");
538
+ await new Promise((resolve2, reject) => {
539
+ (0, import_fluent_ffmpeg.default)(inputPath).outputOptions([
540
+ `-vf fps=${fps},scale=-1:${scale}`,
541
+ "-q:v 2"
542
+ ]).output(outputPattern).on("end", () => resolve2()).on("error", (err) => reject(err)).run();
543
+ });
544
+ return buildFrameList(outputDir, inputPath);
545
+ }
546
+ async function getVideoDuration(inputPath) {
547
+ return new Promise((resolve2, reject) => {
548
+ import_fluent_ffmpeg.default.ffprobe(inputPath, (err, metadata) => {
549
+ if (err) {
550
+ reject(err);
551
+ return;
552
+ }
553
+ resolve2(metadata.format.duration ?? 0);
554
+ });
555
+ });
556
+ }
557
+ async function buildFrameList(framesDir, inputPath) {
558
+ const files = await (0, import_promises2.readdir)(framesDir);
559
+ const jpgFiles = files.filter((f) => f.endsWith(".jpg")).sort();
560
+ if (jpgFiles.length === 0) {
561
+ return [];
562
+ }
563
+ let duration = 0;
564
+ try {
565
+ duration = await getVideoDuration(inputPath);
566
+ } catch {
567
+ logger.debug("Could not determine video duration; using frame index for timestamps");
568
+ }
569
+ return jpgFiles.map((file, index) => ({
570
+ id: index,
571
+ timestamp: duration > 0 && jpgFiles.length > 1 ? duration * index / (jpgFiles.length - 1) : index,
572
+ extractPath: (0, import_node_path3.join)(framesDir, file)
573
+ }));
574
+ }
575
+
576
+ // src/core/input-resolver.ts
577
+ var import_node_path5 = require("path");
578
+
579
+ // src/core/workspace.ts
580
+ var import_promises3 = require("fs/promises");
581
+ var import_node_path4 = require("path");
582
+ var import_sharp2 = __toESM(require("sharp"), 1);
583
+ async function createWorkspace(sessionId) {
584
+ const workspacePath = getTempWorkspaceDir(sessionId);
585
+ await ensureDir((0, import_node_path4.join)(workspacePath, "frames"));
586
+ await ensureDir((0, import_node_path4.join)(workspacePath, "output"));
587
+ return workspacePath;
588
+ }
589
+ async function finalizeOutput(ctx, selectedFrames) {
590
+ const stagingDir = (0, import_node_path4.join)(ctx.workspacePath, "output");
591
+ const outputPath = ctx.options.outputPath;
592
+ const quality = ctx.options.quality;
593
+ const outputFiles = [];
594
+ for (let i = 0; i < selectedFrames.length; i++) {
595
+ const frame = selectedFrames[i];
596
+ const destName = `scene_${String(i + 1).padStart(3, "0")}.jpg`;
597
+ const destPath = (0, import_node_path4.join)(stagingDir, destName);
598
+ await (0, import_sharp2.default)(frame.extractPath).jpeg({ quality, mozjpeg: true }).toFile(destPath);
599
+ outputFiles.push((0, import_node_path4.join)(outputPath, destName));
600
+ }
601
+ await ensureDir((0, import_node_path4.join)(outputPath, ".."));
602
+ await (0, import_promises3.rename)(stagingDir, outputPath);
603
+ return outputFiles;
604
+ }
605
+ async function cleanupWorkspace(workspacePath) {
606
+ if (!workspacePath) return;
607
+ try {
608
+ await (0, import_promises3.rm)(workspacePath, { recursive: true, force: true });
609
+ } catch {
610
+ }
611
+ }
612
+ async function writeInputBuffer(buffer, workspacePath) {
613
+ const inputDir = (0, import_node_path4.join)(workspacePath, "input");
614
+ await ensureDir(inputDir);
615
+ const tempPath = (0, import_node_path4.join)(inputDir, "input.mp4");
616
+ await (0, import_promises3.writeFile)(tempPath, buffer);
617
+ return tempPath;
618
+ }
619
+ async function writeInputFrames(frames, workspacePath) {
620
+ const framesDir = (0, import_node_path4.join)(workspacePath, "frames");
621
+ await ensureDir(framesDir);
622
+ const frameNodes = [];
623
+ for (let i = 0; i < frames.length; i++) {
624
+ const filename = `frame_${String(i).padStart(6, "0")}${FRAME_OUTPUT_EXTENSION}`;
625
+ const extractPath = (0, import_node_path4.join)(framesDir, filename);
626
+ await (0, import_promises3.writeFile)(extractPath, frames[i]);
627
+ frameNodes.push({ id: i, timestamp: i, extractPath });
628
+ }
629
+ return frameNodes;
630
+ }
631
+ async function readFramesAsBuffers(frameNodes, quality) {
632
+ return Promise.all(
633
+ frameNodes.map(
634
+ (f) => (0, import_sharp2.default)(f.extractPath).jpeg({ quality, mozjpeg: true }).toBuffer()
635
+ )
636
+ );
637
+ }
638
+
639
+ // src/core/input-resolver.ts
640
+ function resolveOptions(options) {
641
+ const mode = options.mode;
642
+ const inputPath = mode === "file" ? options.inputPath : void 0;
643
+ const outputPath = options.outputPath ?? (inputPath ? deriveOutputPath(inputPath) : (0, import_node_path5.join)(process.cwd(), "scene-sieve-output"));
644
+ const threshold = options.threshold;
645
+ if (threshold !== void 0 && (threshold <= 0 || threshold > 1)) {
646
+ throw new Error(
647
+ `threshold must be in range (0, 1], received: ${threshold}`
648
+ );
649
+ }
650
+ const hasThreshold = threshold !== void 0;
651
+ const hasExplicitCount = options.count !== void 0;
652
+ const pruneMode = hasThreshold && hasExplicitCount ? "threshold-with-cap" : hasThreshold ? "threshold" : "count";
653
+ return {
654
+ mode,
655
+ inputPath,
656
+ count: options.count ?? DEFAULT_COUNT,
657
+ threshold,
658
+ pruneMode,
659
+ outputPath,
660
+ fps: options.fps ?? DEFAULT_FPS,
661
+ scale: options.scale ?? DEFAULT_SCALE,
662
+ quality: options.quality ?? DEFAULT_QUALITY,
663
+ debug: options.debug ?? false
664
+ };
665
+ }
666
+ async function resolveInput(options, workspacePath) {
667
+ if (options.mode === "file") {
668
+ return { frames: [], resolvedInputPath: options.inputPath };
669
+ }
670
+ if (options.mode === "buffer") {
671
+ const resolvedInputPath = await writeInputBuffer(options.inputBuffer, workspacePath);
672
+ return { frames: [], resolvedInputPath };
673
+ }
674
+ if (options.mode === "frames") {
675
+ const frames = await writeInputFrames(options.inputFrames, workspacePath);
676
+ return { frames };
677
+ }
678
+ throw new Error(`Unsupported input mode: ${options.mode}`);
679
+ }
680
+
681
+ // src/utils/min-heap.ts
682
+ var MinHeap = class {
683
+ h = [];
684
+ get size() {
685
+ return this.h.length;
686
+ }
687
+ push(entry) {
688
+ this.h.push(entry);
689
+ this.siftUp(this.h.length - 1);
690
+ }
691
+ pop() {
692
+ const n = this.h.length;
693
+ if (n === 0) return void 0;
694
+ const top = this.h[0];
695
+ const last = this.h.pop();
696
+ if (n > 1) {
697
+ this.h[0] = last;
698
+ this.siftDown(0);
699
+ }
700
+ return top;
701
+ }
702
+ siftUp(i) {
703
+ while (i > 0) {
704
+ const p = i - 1 >> 1;
705
+ if (this.h[p].score <= this.h[i].score) break;
706
+ [this.h[p], this.h[i]] = [this.h[i], this.h[p]];
707
+ i = p;
708
+ }
709
+ }
710
+ siftDown(i) {
711
+ const n = this.h.length;
712
+ for (; ; ) {
713
+ let m = i;
714
+ const l = 2 * i + 1;
715
+ const r = 2 * i + 2;
716
+ if (l < n && this.h[l].score < this.h[m].score) m = l;
717
+ if (r < n && this.h[r].score < this.h[m].score) m = r;
718
+ if (m === i) break;
719
+ [this.h[m], this.h[i]] = [this.h[i], this.h[m]];
720
+ i = m;
721
+ }
722
+ }
723
+ };
724
+
725
+ // src/core/pruner.ts
726
+ function pruneTo(graph, frames, targetCount) {
727
+ if (frames.length <= targetCount) {
728
+ return new Set(frames.map((f) => f.id));
729
+ }
730
+ const prev = /* @__PURE__ */ new Map();
731
+ const next = /* @__PURE__ */ new Map();
732
+ for (let i = 0; i < frames.length; i++) {
733
+ if (i > 0) prev.set(frames[i].id, frames[i - 1].id);
734
+ if (i < frames.length - 1) next.set(frames[i].id, frames[i + 1].id);
735
+ }
736
+ const edgeScore = /* @__PURE__ */ new Map();
737
+ const heap = new MinHeap();
738
+ for (const edge of graph) {
739
+ edgeScore.set(`${edge.sourceId}:${edge.targetId}`, edge.score);
740
+ heap.push({ score: edge.score, srcId: edge.sourceId, tgtId: edge.targetId });
741
+ }
742
+ const surviving = new Set(frames.map((f) => f.id));
743
+ const firstId = frames[0].id;
744
+ const lastId = frames[frames.length - 1].id;
745
+ while (surviving.size > targetCount && heap.size > 0) {
746
+ const entry = heap.pop();
747
+ if (!surviving.has(entry.srcId) || !surviving.has(entry.tgtId)) continue;
748
+ const key = `${entry.srcId}:${entry.tgtId}`;
749
+ if (edgeScore.get(key) !== entry.score) continue;
750
+ if (entry.tgtId === firstId || entry.tgtId === lastId) continue;
751
+ surviving.delete(entry.tgtId);
752
+ edgeScore.delete(key);
753
+ const tgtNext = next.get(entry.tgtId);
754
+ if (tgtNext !== void 0) {
755
+ const rightKey = `${entry.tgtId}:${tgtNext}`;
756
+ const rightScore = edgeScore.get(rightKey) ?? 0;
757
+ edgeScore.delete(rightKey);
758
+ const newScore = Math.max(entry.score, rightScore);
759
+ edgeScore.set(`${entry.srcId}:${tgtNext}`, newScore);
760
+ heap.push({ score: newScore, srcId: entry.srcId, tgtId: tgtNext });
761
+ next.set(entry.srcId, tgtNext);
762
+ prev.set(tgtNext, entry.srcId);
763
+ } else {
764
+ next.delete(entry.srcId);
765
+ }
766
+ prev.delete(entry.tgtId);
767
+ next.delete(entry.tgtId);
768
+ }
769
+ return surviving;
770
+ }
771
+ function normalizeScores(graph) {
772
+ if (graph.length === 0) return [];
773
+ const safeScores = graph.map(
774
+ (e) => Number.isFinite(e.score) && e.score > 0 ? e.score : 0
775
+ );
776
+ const maxScore = Math.max(...safeScores);
777
+ if (maxScore === 0) return safeScores;
778
+ return safeScores.map((s) => s / maxScore);
779
+ }
780
+ function pruneByThreshold(graph, frames, threshold) {
781
+ if (frames.length === 0) return /* @__PURE__ */ new Set();
782
+ const surviving = /* @__PURE__ */ new Set();
783
+ surviving.add(frames[0].id);
784
+ surviving.add(frames[frames.length - 1].id);
785
+ const normalized = normalizeScores(graph);
786
+ for (let i = 0; i < graph.length; i++) {
787
+ if (normalized[i] >= threshold) {
788
+ surviving.add(graph[i].targetId);
789
+ }
790
+ }
791
+ return surviving;
792
+ }
793
+ function pruneByThresholdWithCap(graph, frames, threshold, maxCount) {
794
+ const thresholdSurvivors = pruneByThreshold(graph, frames, threshold);
795
+ if (thresholdSurvivors.size <= maxCount) {
796
+ return thresholdSurvivors;
797
+ }
798
+ const survivingFrames = frames.filter((f) => thresholdSurvivors.has(f.id));
799
+ const idToOrigIdx = /* @__PURE__ */ new Map();
800
+ for (let i = 0; i < frames.length; i++) {
801
+ idToOrigIdx.set(frames[i].id, i);
802
+ }
803
+ const edgeLookup = /* @__PURE__ */ new Map();
804
+ for (const e of graph) {
805
+ edgeLookup.set(`${e.sourceId}:${e.targetId}`, e.score);
806
+ }
807
+ const syntheticEdges = [];
808
+ for (let i = 0; i < survivingFrames.length - 1; i++) {
809
+ const srcSurvivor = survivingFrames[i];
810
+ const tgtSurvivor = survivingFrames[i + 1];
811
+ const srcOrigIdx = idToOrigIdx.get(srcSurvivor.id);
812
+ const tgtOrigIdx = idToOrigIdx.get(tgtSurvivor.id);
813
+ let minScore = Infinity;
814
+ for (let j = srcOrigIdx; j < tgtOrigIdx; j++) {
815
+ const fromId = frames[j].id;
816
+ const toId = frames[j + 1].id;
817
+ const score = edgeLookup.get(`${fromId}:${toId}`) ?? 0;
818
+ if (score < minScore) {
819
+ minScore = score;
820
+ }
821
+ }
822
+ syntheticEdges.push({
823
+ sourceId: srcSurvivor.id,
824
+ targetId: tgtSurvivor.id,
825
+ score: minScore === Infinity ? 0 : minScore
826
+ });
827
+ }
828
+ return pruneTo(syntheticEdges, survivingFrames, maxCount);
829
+ }
830
+
831
+ // src/core/orchestrator.ts
832
+ async function runPipeline(options) {
833
+ const startTime = Date.now();
834
+ const sessionId = (0, import_node_crypto.randomUUID)();
835
+ const debug = options.debug ?? false;
836
+ if (debug) setDebugMode(true);
837
+ const resolvedOptions = resolveOptions(options);
838
+ const ctx = {
839
+ options: resolvedOptions,
840
+ workspacePath: "",
841
+ frames: [],
842
+ graph: [],
843
+ status: "INIT",
844
+ emitProgress: (percent) => {
845
+ if (options.onProgress && ctx.status !== "INIT" && ctx.status !== "SUCCESS" && ctx.status !== "FAILED") {
846
+ options.onProgress(ctx.status, percent);
847
+ }
848
+ }
849
+ };
850
+ try {
851
+ ctx.workspacePath = await createWorkspace(sessionId);
852
+ logger.debug(`Workspace created: ${ctx.workspacePath}`);
853
+ ctx.status = "EXTRACTING";
854
+ const { frames: resolvedFrames, resolvedInputPath } = await resolveInput(
855
+ options,
856
+ ctx.workspacePath
857
+ );
858
+ if (resolvedOptions.mode === "frames") {
859
+ ctx.frames = resolvedFrames;
860
+ } else {
861
+ const extractCtx = {
862
+ ...ctx,
863
+ options: {
864
+ ...resolvedOptions,
865
+ inputPath: resolvedInputPath
866
+ }
867
+ };
868
+ ctx.frames = await extractFrames(extractCtx);
869
+ }
870
+ ctx.emitProgress(100);
871
+ ctx.status = "ANALYZING";
872
+ ctx.graph = await analyzeFrames(ctx);
873
+ ctx.status = "PRUNING";
874
+ let survivingIds;
875
+ switch (resolvedOptions.pruneMode) {
876
+ case "threshold-with-cap":
877
+ survivingIds = pruneByThresholdWithCap(
878
+ ctx.graph,
879
+ ctx.frames,
880
+ resolvedOptions.threshold,
881
+ resolvedOptions.count
882
+ );
883
+ break;
884
+ case "threshold":
885
+ survivingIds = pruneByThreshold(
886
+ ctx.graph,
887
+ ctx.frames,
888
+ resolvedOptions.threshold
889
+ );
890
+ break;
891
+ case "count":
892
+ default:
893
+ survivingIds = pruneTo(ctx.graph, ctx.frames, resolvedOptions.count);
894
+ break;
895
+ }
896
+ const prunedFrames = ctx.frames.filter((f) => survivingIds.has(f.id));
897
+ ctx.emitProgress(100);
898
+ ctx.status = "FINALIZING";
899
+ let outputFiles = [];
900
+ let outputBuffers;
901
+ if (resolvedOptions.mode === "buffer" || resolvedOptions.mode === "frames") {
902
+ outputBuffers = await readFramesAsBuffers(prunedFrames, resolvedOptions.quality);
903
+ ctx.emitProgress(100);
904
+ } else {
905
+ outputFiles = await finalizeOutput(ctx, prunedFrames);
906
+ ctx.emitProgress(100);
907
+ }
908
+ ctx.status = "SUCCESS";
909
+ logger.success(
910
+ `Extracted ${prunedFrames.length} scenes from ${ctx.frames.length} frames`
911
+ );
912
+ return {
913
+ success: true,
914
+ originalFramesCount: ctx.frames.length,
915
+ prunedFramesCount: prunedFrames.length,
916
+ outputFiles,
917
+ outputBuffers,
918
+ executionTimeMs: Date.now() - startTime
919
+ };
920
+ } catch (error) {
921
+ ctx.status = "FAILED";
922
+ ctx.error = error instanceof Error ? error : new Error(String(error));
923
+ logger.error(`Pipeline failed: ${ctx.error.message}`);
924
+ throw ctx.error;
925
+ } finally {
926
+ if (!resolvedOptions.debug) {
927
+ await cleanupWorkspace(ctx.workspacePath);
928
+ } else {
929
+ logger.debug(`Debug mode: workspace preserved at ${ctx.workspacePath}`);
930
+ }
931
+ }
932
+ }
933
+ // Annotate the CommonJS export names for ESM import in node:
934
+ 0 && (module.exports = {
935
+ extractScenes
936
+ });