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