@lumy-pack/scene-sieve 0.0.14 → 0.2.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/README.md +47 -24
- package/dist/{errors.d.ts → cli/errors/classify-error.d.ts} +5 -0
- package/dist/cli/index.d.ts +3 -0
- package/dist/{utils → cli/options}/parse-options.d.ts +6 -1
- package/dist/cli.mjs +2437 -2126
- package/dist/constants/pipeline-defaults.d.ts +13 -0
- package/dist/core/{analyzer.d.ts → analyzer/analyzer.d.ts} +11 -6
- package/dist/core/{dbscan.d.ts → analyzer/clustering/dbscan.d.ts} +1 -1
- package/dist/core/analyzer/constants/vision-tuning.d.ts +12 -0
- package/dist/core/analyzer/features/feature-diff.d.ts +14 -0
- package/dist/core/analyzer/features/frame-features.d.ts +32 -0
- package/dist/core/analyzer/index.d.ts +3 -0
- package/dist/core/constants/workspace-layout.d.ts +9 -0
- package/dist/core/{extractor.d.ts → extractor/extractor.d.ts} +6 -4
- package/dist/core/extractor/index.d.ts +1 -0
- package/dist/core/index.d.ts +8 -9
- package/dist/core/input-resolver/index.d.ts +1 -0
- package/dist/core/{input-resolver.d.ts → input-resolver/input-resolver.d.ts} +11 -1
- package/dist/core/input-resolver/validation/validate-options.d.ts +8 -0
- package/dist/core/orchestrator/index.d.ts +3 -0
- package/dist/core/{orchestrator.d.ts → orchestrator/orchestrator.d.ts} +1 -1
- package/dist/core/{run-in-worker.d.ts → orchestrator/worker/run-in-worker.d.ts} +5 -1
- package/dist/core/pruner/index.d.ts +1 -0
- package/dist/core/{pruner.d.ts → pruner/pruner.d.ts} +2 -2
- package/dist/{utils/math.d.ts → core/pruner/scoring/normalize-scores.d.ts} +4 -0
- package/dist/core/segmenter/index.d.ts +1 -0
- package/dist/core/{segmenter.d.ts → segmenter/segmenter.d.ts} +11 -11
- package/dist/core/utils/metadata/build-video-metadata.d.ts +14 -0
- package/dist/core/workspace/index.d.ts +1 -0
- package/dist/core/{workspace.d.ts → workspace/workspace.d.ts} +1 -1
- package/dist/index.cjs +1854 -1486
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +1836 -1455
- package/dist/pipeline-worker.mjs +1734 -1474
- package/dist/types/index.d.ts +25 -0
- package/package.json +5 -4
- package/dist/constants.d.ts +0 -32
- /package/dist/{commands → cli/commands}/Sieve.d.ts +0 -0
- /package/dist/{utils → cli/commands}/command-registry.d.ts +0 -0
- /package/dist/{components → cli/components}/PhaseStep.d.ts +0 -0
- /package/dist/{components → cli/components}/ProgressBar.d.ts +0 -0
- /package/dist/core/{pipeline-worker.d.ts → orchestrator/worker/pipeline-worker.d.ts} +0 -0
- /package/dist/{utils → core/pruner/heap}/min-heap.d.ts +0 -0
- /package/dist/{utils → core/segmenter/scheduling}/concurrency.d.ts +0 -0
- /package/dist/{utils → core/utils/filesystem}/paths.d.ts +0 -0
- /package/dist/{utils → logging}/logger.d.ts +0 -0
package/dist/index.mjs
CHANGED
|
@@ -1,1565 +1,1946 @@
|
|
|
1
|
-
|
|
2
|
-
import { randomUUID
|
|
3
|
-
import { filter
|
|
4
|
-
|
|
5
|
-
// src/utils/logger.ts
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { filter, map } from "@winglet/common-utils";
|
|
6
4
|
import pc from "picocolors";
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
import sharp from "sharp";
|
|
6
|
+
import { mkdir, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
|
7
|
+
import { basename, extname, join, resolve } from "node:path";
|
|
8
|
+
import { path } from "@ffprobe-installer/ffprobe";
|
|
9
|
+
import { execa } from "execa";
|
|
10
|
+
import ffmpegPath from "ffmpeg-static";
|
|
11
|
+
import { homedir, tmpdir } from "node:os";
|
|
12
|
+
|
|
13
|
+
//#region \0rolldown/runtime.js
|
|
14
|
+
var __esmMin = (fn, res, err) => () => {
|
|
15
|
+
if (err) throw err[0];
|
|
16
|
+
try {
|
|
17
|
+
return fn && (res = fn(fn = 0)), res;
|
|
18
|
+
} catch (e) {
|
|
19
|
+
throw err = [e], e;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
//#endregion
|
|
24
|
+
//#region src/logging/logger.ts
|
|
9
25
|
function setDebugMode(enabled) {
|
|
10
|
-
|
|
26
|
+
debugMode = enabled;
|
|
11
27
|
}
|
|
12
28
|
function timestamp() {
|
|
13
|
-
|
|
29
|
+
return (/* @__PURE__ */ new Date()).toLocaleTimeString("en-US", { hour12: false });
|
|
14
30
|
}
|
|
15
|
-
var
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
if (debugMode) {
|
|
41
|
-
if (jsonMode) {
|
|
42
|
-
process.stderr.write(`${pc.gray(`[${timestamp()}] debug`)} ${message}
|
|
43
|
-
`);
|
|
44
|
-
} else {
|
|
45
|
-
console.log(`${pc.gray(`[${timestamp()}] debug`)} ${message}`);
|
|
46
|
-
}
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
};
|
|
31
|
+
var debugMode, jsonMode, logger;
|
|
32
|
+
var init_logger = __esmMin((() => {
|
|
33
|
+
debugMode = false;
|
|
34
|
+
jsonMode = false;
|
|
35
|
+
logger = {
|
|
36
|
+
info(message) {
|
|
37
|
+
if (jsonMode) process.stderr.write(`${pc.blue("info")} ${message}\n`);
|
|
38
|
+
else console.log(`${pc.blue("info")} ${message}`);
|
|
39
|
+
},
|
|
40
|
+
success(message) {
|
|
41
|
+
if (jsonMode) process.stderr.write(`${pc.green("done")} ${message}\n`);
|
|
42
|
+
else console.log(`\n${pc.green("done")} ${message}`);
|
|
43
|
+
},
|
|
44
|
+
warn(message) {
|
|
45
|
+
console.warn(`${pc.yellow("warn")} ${message}`);
|
|
46
|
+
},
|
|
47
|
+
error(message) {
|
|
48
|
+
console.error(`${pc.red("error")} ${message}`);
|
|
49
|
+
},
|
|
50
|
+
debug(message) {
|
|
51
|
+
if (debugMode) if (jsonMode) process.stderr.write(`${pc.gray(`[${timestamp()}] debug`)} ${message}\n`);
|
|
52
|
+
else console.log(`${pc.gray(`[${timestamp()}] debug`)} ${message}`);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}));
|
|
50
56
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/constants/pipeline-defaults.ts
|
|
59
|
+
var DEFAULT_THRESHOLD, IOU_THRESHOLD;
|
|
60
|
+
var init_pipeline_defaults = __esmMin((() => {
|
|
61
|
+
DEFAULT_THRESHOLD = .5;
|
|
62
|
+
IOU_THRESHOLD = .9;
|
|
63
|
+
}));
|
|
55
64
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
var
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
var DEFAULT_QUALITY = 80;
|
|
65
|
-
var DEFAULT_MAX_FRAMES = 300;
|
|
66
|
-
var NORMALIZATION_LOGISTIC_K = 3;
|
|
67
|
-
var NORMALIZATION_ALPHA = 0.4;
|
|
68
|
-
var NORMALIZATION_MAD_COEFFICIENT = 1.4826;
|
|
69
|
-
var NORMALIZATION_MIN_SAMPLE_SIZE = 10;
|
|
70
|
-
var WORKSPACE_PREFIX = `${APP_NAME}-`;
|
|
71
|
-
var TEMP_BASE_DIR = tmpdir();
|
|
72
|
-
var FRAME_OUTPUT_EXTENSION = ".jpg";
|
|
73
|
-
var FRAME_FILENAME_PATTERN = "frame_%06d.jpg";
|
|
74
|
-
var OPENCV_BATCH_SIZE = 10;
|
|
75
|
-
var DBSCAN_ALPHA = 0.03;
|
|
76
|
-
var DBSCAN_MIN_PTS = 4;
|
|
77
|
-
var IOU_THRESHOLD = 0.9;
|
|
78
|
-
var DECAY_LAMBDA = 0.95;
|
|
79
|
-
var ANIMATION_FRAME_THRESHOLD = 5;
|
|
80
|
-
var MATCH_DISTANCE_THRESHOLD = 0.25;
|
|
81
|
-
var PIXELDIFF_GAUSSIAN_KERNEL = 3;
|
|
82
|
-
var PIXELDIFF_BINARY_THRESHOLD = 30;
|
|
83
|
-
var PIXELDIFF_CONTOUR_MIN_AREA = 100;
|
|
84
|
-
var PIXELDIFF_SAMPLE_SPACING = 8;
|
|
85
|
-
var DEFAULT_MAX_SEGMENT_DURATION = 300;
|
|
86
|
-
var DEFAULT_SEGMENT_CONCURRENCY = 2;
|
|
87
|
-
function getTempWorkspaceDir(sessionId) {
|
|
88
|
-
return join(TEMP_BASE_DIR, `${WORKSPACE_PREFIX}${sessionId}`);
|
|
89
|
-
}
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region src/core/analyzer/constants/vision-tuning.ts
|
|
67
|
+
var DBSCAN_ALPHA, DECAY_LAMBDA, MATCH_DISTANCE_THRESHOLD;
|
|
68
|
+
var init_vision_tuning = __esmMin((() => {
|
|
69
|
+
DBSCAN_ALPHA = .03;
|
|
70
|
+
DECAY_LAMBDA = .95;
|
|
71
|
+
MATCH_DISTANCE_THRESHOLD = .25;
|
|
72
|
+
}));
|
|
90
73
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
74
|
+
//#endregion
|
|
75
|
+
//#region src/core/analyzer/clustering/dbscan.ts
|
|
76
|
+
/**
|
|
77
|
+
* DBSCAN clustering with resolution-independent eps.
|
|
78
|
+
* eps = alpha * sqrt(width^2 + height^2)
|
|
79
|
+
*/
|
|
94
80
|
function dbscan(points, imageWidth, imageHeight, alpha, minPts) {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
81
|
+
if (points.length === 0) return {
|
|
82
|
+
labels: [],
|
|
83
|
+
boundingBoxes: []
|
|
84
|
+
};
|
|
85
|
+
const eps = (alpha ?? .03) * Math.sqrt(imageWidth ** 2 + imageHeight ** 2);
|
|
86
|
+
const epsSquared = eps * eps;
|
|
87
|
+
const minPoints = minPts ?? 4;
|
|
88
|
+
const labels = new Array(points.length).fill(UNVISITED);
|
|
89
|
+
let clusterId = 0;
|
|
90
|
+
for (let i = 0; i < points.length; i++) {
|
|
91
|
+
if (labels[i] !== UNVISITED) continue;
|
|
92
|
+
const neighbors = findNeighbors(points, i, epsSquared);
|
|
93
|
+
if (neighbors.length < minPoints) {
|
|
94
|
+
labels[i] = NOISE;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
labels[i] = clusterId;
|
|
98
|
+
const seeds = [...neighbors];
|
|
99
|
+
const seedSet = new Set(seeds);
|
|
100
|
+
for (let si = 0; si < seeds.length; si++) {
|
|
101
|
+
const q = seeds[si];
|
|
102
|
+
if (labels[q] === NOISE) labels[q] = clusterId;
|
|
103
|
+
if (labels[q] !== UNVISITED) continue;
|
|
104
|
+
labels[q] = clusterId;
|
|
105
|
+
const qNeighbors = findNeighbors(points, q, epsSquared);
|
|
106
|
+
if (qNeighbors.length >= minPoints) {
|
|
107
|
+
for (const n of qNeighbors) if (!seedSet.has(n)) {
|
|
108
|
+
seedSet.add(n);
|
|
109
|
+
seeds.push(n);
|
|
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 {
|
|
137
|
+
labels,
|
|
138
|
+
boundingBoxes
|
|
139
|
+
};
|
|
154
140
|
}
|
|
155
141
|
function findNeighbors(points, idx, epsSquared) {
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
return neighbors;
|
|
142
|
+
const p = points[idx];
|
|
143
|
+
const neighbors = [];
|
|
144
|
+
for (let i = 0; i < points.length; i++) {
|
|
145
|
+
if (i === idx) continue;
|
|
146
|
+
const q = points[i];
|
|
147
|
+
if ((p.x - q.x) ** 2 + (p.y - q.y) ** 2 <= epsSquared) neighbors.push(i);
|
|
148
|
+
}
|
|
149
|
+
return neighbors;
|
|
167
150
|
}
|
|
151
|
+
var UNVISITED, NOISE;
|
|
152
|
+
var init_dbscan = __esmMin((() => {
|
|
153
|
+
init_vision_tuning();
|
|
154
|
+
UNVISITED = -2;
|
|
155
|
+
NOISE = -1;
|
|
156
|
+
}));
|
|
168
157
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region src/core/analyzer/features/feature-diff.ts
|
|
160
|
+
/**
|
|
161
|
+
* Match prev to next with Hamming k=2, crossCheck=false and strict ratio 0.25.
|
|
162
|
+
* @param cvLib - Initialized OpenCV runtime.
|
|
163
|
+
* @param prev - Previous frame's live features, owned by the caller.
|
|
164
|
+
* @param next - Next frame's live features, owned by the caller.
|
|
165
|
+
* @returns Unmatched next-frame coordinates without changing input ownership.
|
|
166
|
+
* @throws Propagates matching errors after releasing temporary native handles.
|
|
167
|
+
*/
|
|
168
|
+
function computeNewPoints(cvLib, prev, next) {
|
|
169
|
+
let matcher = null;
|
|
170
|
+
let matches = null;
|
|
171
|
+
try {
|
|
172
|
+
const matchedIndices = /* @__PURE__ */ new Set();
|
|
173
|
+
if (prev.descriptors.rows > 0 && next.descriptors.rows > 0) try {
|
|
174
|
+
matcher = new cvLib.BFMatcher(cvLib.NORM_HAMMING, false);
|
|
175
|
+
matches = new cvLib.DMatchVectorVector();
|
|
176
|
+
matcher.knnMatch(prev.descriptors, next.descriptors, matches, 2);
|
|
177
|
+
for (let i = 0; i < matches.size(); i++) {
|
|
178
|
+
const pair = matches.get(i);
|
|
179
|
+
try {
|
|
180
|
+
if (pair.size() < 2) continue;
|
|
181
|
+
const best = pair.get(0);
|
|
182
|
+
const second = pair.get(1);
|
|
183
|
+
if (best.distance < .25 * second.distance) matchedIndices.add(best.trainIdx);
|
|
184
|
+
} finally {
|
|
185
|
+
pair.delete();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
} finally {
|
|
189
|
+
matcher?.delete();
|
|
190
|
+
}
|
|
191
|
+
const points = [];
|
|
192
|
+
for (let i = 0; i < next.keypoints.size(); i++) if (!matchedIndices.has(i)) {
|
|
193
|
+
const { x, y } = next.keypoints.get(i).pt;
|
|
194
|
+
points.push({
|
|
195
|
+
x,
|
|
196
|
+
y
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
return points;
|
|
200
|
+
} finally {
|
|
201
|
+
matches?.delete();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
var init_feature_diff = __esmMin((() => {
|
|
205
|
+
init_vision_tuning();
|
|
206
|
+
}));
|
|
207
|
+
|
|
208
|
+
//#endregion
|
|
209
|
+
//#region src/core/analyzer/features/frame-features.ts
|
|
210
|
+
/**
|
|
211
|
+
* Detect one frame's features without retaining its image or mask.
|
|
212
|
+
* @param cvLib - Initialized OpenCV runtime.
|
|
213
|
+
* @param akaze - Detector owned and released by the caller.
|
|
214
|
+
* @param frame - Grayscale bytes with matching width and height.
|
|
215
|
+
* @returns Feature handles that the caller must delete.
|
|
216
|
+
* @throws Propagates native errors after releasing partial allocations.
|
|
217
|
+
*/
|
|
218
|
+
function computeFrameFeatures(cvLib, akaze, frame) {
|
|
219
|
+
let image = null;
|
|
220
|
+
let mask = null;
|
|
221
|
+
let keypoints = null;
|
|
222
|
+
let descriptors = null;
|
|
223
|
+
try {
|
|
224
|
+
image = new cvLib.Mat(frame.height, frame.width, cvLib.CV_8UC1);
|
|
225
|
+
image.data.set(frame.data);
|
|
226
|
+
mask = new cvLib.Mat();
|
|
227
|
+
keypoints = new cvLib.KeyPointVector();
|
|
228
|
+
descriptors = new cvLib.Mat();
|
|
229
|
+
akaze.detectAndCompute(image, mask, keypoints, descriptors);
|
|
230
|
+
const ownedKeypoints = keypoints;
|
|
231
|
+
const ownedDescriptors = descriptors;
|
|
232
|
+
let deleted = false;
|
|
233
|
+
const features = {
|
|
234
|
+
width: frame.width,
|
|
235
|
+
height: frame.height,
|
|
236
|
+
keypoints: ownedKeypoints,
|
|
237
|
+
descriptors: ownedDescriptors,
|
|
238
|
+
/** Release the transferred handles exactly once. */
|
|
239
|
+
delete() {
|
|
240
|
+
if (deleted) return;
|
|
241
|
+
deleted = true;
|
|
242
|
+
try {
|
|
243
|
+
ownedKeypoints.delete();
|
|
244
|
+
} finally {
|
|
245
|
+
ownedDescriptors.delete();
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
keypoints = null;
|
|
250
|
+
descriptors = null;
|
|
251
|
+
return features;
|
|
252
|
+
} finally {
|
|
253
|
+
image?.delete();
|
|
254
|
+
mask?.delete();
|
|
255
|
+
keypoints?.delete();
|
|
256
|
+
descriptors?.delete();
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
var init_frame_features = __esmMin((() => {}));
|
|
260
|
+
|
|
261
|
+
//#endregion
|
|
262
|
+
//#region src/core/analyzer/analyzer.ts
|
|
173
263
|
async function ensureOpenCV() {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
}
|
|
190
|
-
return cvReady;
|
|
264
|
+
if (!cvReady) cvReady = (async () => {
|
|
265
|
+
const cvObj = require("@techstark/opencv-js");
|
|
266
|
+
delete cvObj.then;
|
|
267
|
+
if (cvObj.Mat) return cvObj;
|
|
268
|
+
return new Promise((resolve, reject) => {
|
|
269
|
+
const timeout = setTimeout(() => {
|
|
270
|
+
reject(/* @__PURE__ */ new Error("OpenCV WASM initialization timed out after 30s"));
|
|
271
|
+
}, OPENCV_INIT_TIMEOUT_MS);
|
|
272
|
+
cvObj.onRuntimeInitialized = () => {
|
|
273
|
+
clearTimeout(timeout);
|
|
274
|
+
resolve(cvObj);
|
|
275
|
+
};
|
|
276
|
+
});
|
|
277
|
+
})();
|
|
278
|
+
return cvReady;
|
|
191
279
|
}
|
|
192
280
|
async function preprocessFrame(framePath, scale) {
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
281
|
+
const { data, info } = await sharp(framePath).resize({
|
|
282
|
+
width: scale,
|
|
283
|
+
withoutEnlargement: true
|
|
284
|
+
}).grayscale().blur(1).raw().toBuffer({ resolveWithObject: true });
|
|
285
|
+
return {
|
|
286
|
+
data: new Uint8Array(data.buffer, data.byteOffset, data.byteLength),
|
|
287
|
+
width: info.width,
|
|
288
|
+
height: info.height
|
|
289
|
+
};
|
|
199
290
|
}
|
|
200
291
|
function computeIoU(a, b) {
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
const aArea = a.width * a.height;
|
|
210
|
-
const bArea = b.width * b.height;
|
|
211
|
-
const union = aArea + bArea - intersection;
|
|
212
|
-
return union === 0 ? 0 : intersection / union;
|
|
213
|
-
}
|
|
214
|
-
var IoUTracker = class {
|
|
215
|
-
constructor(fps = DEFAULT_FPS, iouThreshold = IOU_THRESHOLD, animationThreshold = ANIMATION_FRAME_THRESHOLD) {
|
|
216
|
-
this.fps = fps;
|
|
217
|
-
this.iouThreshold = iouThreshold;
|
|
218
|
-
this.animationThreshold = animationThreshold;
|
|
219
|
-
}
|
|
220
|
-
regions = [];
|
|
221
|
-
extractedAnimations = [];
|
|
222
|
-
update(boxes, pairIndex) {
|
|
223
|
-
const animationIndices = /* @__PURE__ */ new Set();
|
|
224
|
-
const matched = /* @__PURE__ */ new Set();
|
|
225
|
-
for (let bi = 0; bi < boxes.length; bi++) {
|
|
226
|
-
const box = boxes[bi];
|
|
227
|
-
let bestIoU = 0;
|
|
228
|
-
let bestRegionIdx = -1;
|
|
229
|
-
for (let ri = 0; ri < this.regions.length; ri++) {
|
|
230
|
-
if (matched.has(ri)) continue;
|
|
231
|
-
const iou = computeIoU(box, this.regions[ri].box);
|
|
232
|
-
if (iou > bestIoU) {
|
|
233
|
-
bestIoU = iou;
|
|
234
|
-
bestRegionIdx = ri;
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
if (bestIoU > this.iouThreshold && bestRegionIdx !== -1) {
|
|
238
|
-
const region = this.regions[bestRegionIdx];
|
|
239
|
-
const gap = pairIndex - region.lastSeen;
|
|
240
|
-
region.box = box;
|
|
241
|
-
region.consecutiveCount++;
|
|
242
|
-
region.lastSeen = pairIndex;
|
|
243
|
-
region.weight *= Math.pow(DECAY_LAMBDA, gap);
|
|
244
|
-
matched.add(bestRegionIdx);
|
|
245
|
-
if (region.consecutiveCount >= this.animationThreshold) {
|
|
246
|
-
animationIndices.add(bi);
|
|
247
|
-
}
|
|
248
|
-
} else {
|
|
249
|
-
this.regions.push({
|
|
250
|
-
box,
|
|
251
|
-
consecutiveCount: 1,
|
|
252
|
-
firstSeen: pairIndex,
|
|
253
|
-
lastSeen: pairIndex,
|
|
254
|
-
weight: 1
|
|
255
|
-
});
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
for (let ri = 0; ri < this.regions.length; ri++) {
|
|
259
|
-
if (!matched.has(ri)) {
|
|
260
|
-
const gap = pairIndex - this.regions[ri].lastSeen;
|
|
261
|
-
this.regions[ri].weight *= Math.pow(DECAY_LAMBDA, gap);
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
for (let i = 0; i < this.regions.length; i++) {
|
|
265
|
-
const region = this.regions[i];
|
|
266
|
-
if (region.weight <= 0.01 && !matched.has(i)) {
|
|
267
|
-
this.collectAnimation(region);
|
|
268
|
-
}
|
|
269
|
-
}
|
|
270
|
-
this.regions = filter(
|
|
271
|
-
this.regions,
|
|
272
|
-
(r, i) => r.weight > 0.01 || matched.has(i)
|
|
273
|
-
);
|
|
274
|
-
return animationIndices;
|
|
275
|
-
}
|
|
276
|
-
collectAnimation(region) {
|
|
277
|
-
if (region.consecutiveCount >= this.animationThreshold) {
|
|
278
|
-
const durationMs = region.consecutiveCount / this.fps * 1e3;
|
|
279
|
-
this.extractedAnimations.push({
|
|
280
|
-
type: "loading_spinner",
|
|
281
|
-
// 기본값으로 loading_spinner 사용
|
|
282
|
-
boundingBox: region.box,
|
|
283
|
-
startFrameId: region.firstSeen,
|
|
284
|
-
endFrameId: region.lastSeen,
|
|
285
|
-
durationMs
|
|
286
|
-
});
|
|
287
|
-
}
|
|
288
|
-
}
|
|
289
|
-
flushAndGetAnimations() {
|
|
290
|
-
for (const region of this.regions) {
|
|
291
|
-
this.collectAnimation(region);
|
|
292
|
-
}
|
|
293
|
-
this.regions = [];
|
|
294
|
-
return this.extractedAnimations;
|
|
295
|
-
}
|
|
296
|
-
getAnimationWeight(boxIndex, boxes) {
|
|
297
|
-
if (boxIndex >= boxes.length) return 0;
|
|
298
|
-
const box = boxes[boxIndex];
|
|
299
|
-
let maxWeight = 0;
|
|
300
|
-
for (const region of this.regions) {
|
|
301
|
-
if (region.consecutiveCount >= this.animationThreshold) {
|
|
302
|
-
const iou = computeIoU(box, region.box);
|
|
303
|
-
if (iou > this.iouThreshold) {
|
|
304
|
-
maxWeight = Math.max(maxWeight, region.weight);
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
}
|
|
308
|
-
return maxWeight;
|
|
309
|
-
}
|
|
310
|
-
};
|
|
311
|
-
async function computeAKAZEDiff(cvLib, frame1, frame2) {
|
|
312
|
-
const cv = cvLib;
|
|
313
|
-
const mat1 = new cv.Mat(frame1.height, frame1.width, cv.CV_8UC1);
|
|
314
|
-
mat1.data.set(frame1.data);
|
|
315
|
-
const mat2 = new cv.Mat(frame2.height, frame2.width, cv.CV_8UC1);
|
|
316
|
-
mat2.data.set(frame2.data);
|
|
317
|
-
const kp1 = new cvLib.KeyPointVector();
|
|
318
|
-
const kp2 = new cvLib.KeyPointVector();
|
|
319
|
-
const desc1 = new cvLib.Mat();
|
|
320
|
-
const desc2 = new cvLib.Mat();
|
|
321
|
-
const mask1 = new cvLib.Mat();
|
|
322
|
-
const mask2 = new cvLib.Mat();
|
|
323
|
-
const akaze = new cvLib.AKAZE();
|
|
324
|
-
let matches = null;
|
|
325
|
-
try {
|
|
326
|
-
akaze.detectAndCompute(mat1, mask1, kp1, desc1);
|
|
327
|
-
akaze.detectAndCompute(mat2, mask2, kp2, desc2);
|
|
328
|
-
const matchedKp1Indices = /* @__PURE__ */ new Set();
|
|
329
|
-
const matchedKp2Indices = /* @__PURE__ */ new Set();
|
|
330
|
-
if (desc1.rows > 0 && desc2.rows > 0) {
|
|
331
|
-
const matcher = new cvLib.BFMatcher(cvLib.NORM_HAMMING, false);
|
|
332
|
-
try {
|
|
333
|
-
matches = new cvLib.DMatchVectorVector();
|
|
334
|
-
matcher.knnMatch(desc1, desc2, matches, 2);
|
|
335
|
-
for (let i = 0; i < matches.size(); i++) {
|
|
336
|
-
const pair = matches.get(i);
|
|
337
|
-
if (pair.size() < 2) continue;
|
|
338
|
-
const m0 = pair.get(0);
|
|
339
|
-
const m1 = pair.get(1);
|
|
340
|
-
if (m0.distance < MATCH_DISTANCE_THRESHOLD * m1.distance) {
|
|
341
|
-
matchedKp1Indices.add(m0.queryIdx);
|
|
342
|
-
matchedKp2Indices.add(m0.trainIdx);
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
} finally {
|
|
346
|
-
matcher.delete();
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
const sNew = [];
|
|
350
|
-
for (let i = 0; i < kp2.size(); i++) {
|
|
351
|
-
if (!matchedKp2Indices.has(i)) {
|
|
352
|
-
const pt = kp2.get(i).pt;
|
|
353
|
-
sNew.push({ x: pt.x, y: pt.y });
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
const sLoss = [];
|
|
357
|
-
for (let i = 0; i < kp1.size(); i++) {
|
|
358
|
-
if (!matchedKp1Indices.has(i)) {
|
|
359
|
-
const pt = kp1.get(i).pt;
|
|
360
|
-
sLoss.push({ x: pt.x, y: pt.y });
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
return { sNew, sLoss };
|
|
364
|
-
} finally {
|
|
365
|
-
mat1.delete();
|
|
366
|
-
mat2.delete();
|
|
367
|
-
kp1.delete();
|
|
368
|
-
kp2.delete();
|
|
369
|
-
desc1.delete();
|
|
370
|
-
desc2.delete();
|
|
371
|
-
mask1.delete();
|
|
372
|
-
mask2.delete();
|
|
373
|
-
akaze.delete();
|
|
374
|
-
if (matches) matches.delete();
|
|
375
|
-
}
|
|
292
|
+
const ix1 = Math.max(a.x, b.x);
|
|
293
|
+
const iy1 = Math.max(a.y, b.y);
|
|
294
|
+
const ix2 = Math.min(a.x + a.width, b.x + b.width);
|
|
295
|
+
const iy2 = Math.min(a.y + a.height, b.y + b.height);
|
|
296
|
+
const intersection = Math.max(0, ix2 - ix1) * Math.max(0, iy2 - iy1);
|
|
297
|
+
if (intersection === 0) return 0;
|
|
298
|
+
const union = a.width * a.height + b.width * b.height - intersection;
|
|
299
|
+
return union === 0 ? 0 : intersection / union;
|
|
376
300
|
}
|
|
301
|
+
/**
|
|
302
|
+
* Pixel-level difference fallback for AKAZE blind spots.
|
|
303
|
+
*
|
|
304
|
+
* When AKAZE produces sparse results (typical for UI screen recordings
|
|
305
|
+
* where form fields, dropdowns, or overlays change), this function
|
|
306
|
+
* detects changed regions via cv.absdiff and generates synthetic
|
|
307
|
+
* Point2D[] that feed into the existing DBSCAN → IoU → G(t) pipeline.
|
|
308
|
+
*
|
|
309
|
+
* Algorithm:
|
|
310
|
+
* 1. absdiff(frame1, frame2) → grayscale difference
|
|
311
|
+
* 2. GaussianBlur → reduce JPEG compression noise
|
|
312
|
+
* 3. threshold → binary mask of significant changes
|
|
313
|
+
* 4. findContours → bounding rects of changed regions
|
|
314
|
+
* 5. Grid sampling within each bounding rect → Point2D[]
|
|
315
|
+
*
|
|
316
|
+
* @param cvLib - Initialized OpenCV runtime shared by the analyzer.
|
|
317
|
+
* @param frame1 - Previous grayscale frame, with the same dimensions as frame2.
|
|
318
|
+
* @param frame2 - Next grayscale frame, with the same dimensions as frame1.
|
|
319
|
+
* @returns Grid-sampled points from changed regions.
|
|
320
|
+
* @throws Propagates allocation or OpenCV errors after releasing acquired handles.
|
|
321
|
+
*/
|
|
377
322
|
function computePixelDiff(cvLib, frame1, frame2) {
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
blurred.delete();
|
|
426
|
-
binary.delete();
|
|
427
|
-
contours.delete();
|
|
428
|
-
hierarchy.delete();
|
|
429
|
-
}
|
|
323
|
+
const cv = cvLib;
|
|
324
|
+
let mat1 = null;
|
|
325
|
+
let mat2 = null;
|
|
326
|
+
let diff = null;
|
|
327
|
+
let blurred = null;
|
|
328
|
+
let binary = null;
|
|
329
|
+
let contours = null;
|
|
330
|
+
let hierarchy = null;
|
|
331
|
+
try {
|
|
332
|
+
mat1 = new cv.Mat(frame1.height, frame1.width, cv.CV_8UC1);
|
|
333
|
+
mat2 = new cv.Mat(frame2.height, frame2.width, cv.CV_8UC1);
|
|
334
|
+
diff = new cv.Mat();
|
|
335
|
+
blurred = new cv.Mat();
|
|
336
|
+
binary = new cv.Mat();
|
|
337
|
+
contours = new cv.MatVector();
|
|
338
|
+
hierarchy = new cv.Mat();
|
|
339
|
+
mat1.data.set(frame1.data);
|
|
340
|
+
mat2.data.set(frame2.data);
|
|
341
|
+
cv.absdiff(mat1, mat2, diff);
|
|
342
|
+
const ksize = new cv.Size(3, 3);
|
|
343
|
+
cv.GaussianBlur(diff, blurred, ksize, 0);
|
|
344
|
+
cv.threshold(blurred, binary, 30, 255, cv.THRESH_BINARY);
|
|
345
|
+
cv.findContours(binary, contours, hierarchy, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE);
|
|
346
|
+
const points = [];
|
|
347
|
+
for (let c = 0; c < contours.size(); c++) {
|
|
348
|
+
const contour = contours.get(c);
|
|
349
|
+
try {
|
|
350
|
+
const rect = cv.boundingRect(contour);
|
|
351
|
+
if (rect.width * rect.height < 100) continue;
|
|
352
|
+
for (let y = rect.y; y < rect.y + rect.height; y += 8) for (let x = rect.x; x < rect.x + rect.width; x += 8) points.push({
|
|
353
|
+
x,
|
|
354
|
+
y
|
|
355
|
+
});
|
|
356
|
+
} finally {
|
|
357
|
+
contour.delete();
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return points;
|
|
361
|
+
} finally {
|
|
362
|
+
mat1?.delete();
|
|
363
|
+
mat2?.delete();
|
|
364
|
+
diff?.delete();
|
|
365
|
+
blurred?.delete();
|
|
366
|
+
binary?.delete();
|
|
367
|
+
contours?.delete();
|
|
368
|
+
hierarchy?.delete();
|
|
369
|
+
}
|
|
430
370
|
}
|
|
431
371
|
function computeInformationGain(clusters, clusterPoints, imageArea, animationIndices, animationWeights) {
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
}
|
|
447
|
-
return gain;
|
|
372
|
+
if (clusters.length === 0) return 0;
|
|
373
|
+
let gain = 0;
|
|
374
|
+
for (let i = 0; i < clusters.length; i++) {
|
|
375
|
+
const box = clusters[i];
|
|
376
|
+
const clusterArea = box.width * box.height;
|
|
377
|
+
if (clusterArea <= 0) continue;
|
|
378
|
+
let contribution = clusterArea / imageArea * (clusterPoints[i] / clusterArea);
|
|
379
|
+
if (animationIndices.has(i)) {
|
|
380
|
+
const animWeight = animationWeights[i] ?? 0;
|
|
381
|
+
contribution *= 1 - animWeight;
|
|
382
|
+
}
|
|
383
|
+
gain += contribution;
|
|
384
|
+
}
|
|
385
|
+
return gain;
|
|
448
386
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
387
|
+
/**
|
|
388
|
+
* Analyze one batch, retaining its boundary frame for the following batch.
|
|
389
|
+
* @param cvLib - Initialized OpenCV runtime.
|
|
390
|
+
* @param akaze - Detector owned by analyzeFrames.
|
|
391
|
+
* @param frames - Boundary frame followed by new adjacent frames.
|
|
392
|
+
* @param carry - Boundary bytes and live features transferred from the previous batch.
|
|
393
|
+
* @param scale - Maximum preprocessing width.
|
|
394
|
+
* @param tracker - Stateful animation tracker shared across batches.
|
|
395
|
+
* @param pairOffset - Global position of this batch's first pair.
|
|
396
|
+
* @returns Scores, pair failure count, and ownership of the final frame's features.
|
|
397
|
+
*/
|
|
398
|
+
async function analyzeBatch(cvLib, akaze, frames, carry, scale, tracker, pairOffset) {
|
|
399
|
+
const edges = [];
|
|
400
|
+
let failures = 0;
|
|
401
|
+
let prev = carry?.features ?? null;
|
|
402
|
+
let next = null;
|
|
403
|
+
try {
|
|
404
|
+
const preprocessed = await Promise.all(map(frames, (f, index) => index === 0 && carry ? carry.preprocessed : preprocessFrame(f.extractPath, scale)));
|
|
405
|
+
const imageWidth = preprocessed[0]?.width ?? scale;
|
|
406
|
+
const imageHeight = preprocessed[0]?.height ?? Math.round(scale * 9 / 16);
|
|
407
|
+
const imageArea = imageWidth * imageHeight;
|
|
408
|
+
for (let i = 0; i < frames.length - 1; i++) {
|
|
409
|
+
const pairIndex = pairOffset + i;
|
|
410
|
+
try {
|
|
411
|
+
prev ??= computeFrameFeatures(cvLib, akaze, preprocessed[i]);
|
|
412
|
+
next = computeFrameFeatures(cvLib, akaze, preprocessed[i + 1]);
|
|
413
|
+
let dbscanResult = dbscan(computeNewPoints(cvLib, prev, next), imageWidth, imageHeight);
|
|
414
|
+
let clusters = dbscanResult.boundingBoxes;
|
|
415
|
+
if (clusters.length === 0) {
|
|
416
|
+
const pixelDiffPoints = computePixelDiff(cvLib, preprocessed[i], preprocessed[i + 1]);
|
|
417
|
+
if (pixelDiffPoints.length > 0) {
|
|
418
|
+
logger.debug(`Edge ${frames[i].id}->${frames[i + 1].id}: pixel-diff fallback (${pixelDiffPoints.length} points)`);
|
|
419
|
+
dbscanResult = dbscan(pixelDiffPoints, imageWidth, imageHeight, void 0, 2);
|
|
420
|
+
clusters = dbscanResult.boundingBoxes;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
const clusterPointCounts = new Array(clusters.length).fill(0);
|
|
424
|
+
for (const label of dbscanResult.labels) if (label >= 0) clusterPointCounts[label]++;
|
|
425
|
+
const animationIndices = tracker.update(clusters, pairIndex);
|
|
426
|
+
const animationWeights = map(clusters, (_, ci) => animationIndices.has(ci) ? tracker.getAnimationWeight(ci, clusters) : 0);
|
|
427
|
+
const score = computeInformationGain(clusters, clusterPointCounts, imageArea, animationIndices, animationWeights);
|
|
428
|
+
logger.debug(`Edge ${frames[i].id}->${frames[i + 1].id} G(t)=${score.toFixed(6)}`);
|
|
429
|
+
edges.push({
|
|
430
|
+
sourceId: frames[i].id,
|
|
431
|
+
targetId: frames[i + 1].id,
|
|
432
|
+
score
|
|
433
|
+
});
|
|
434
|
+
} catch (err) {
|
|
435
|
+
logger.warn(`Frame pair analysis failed: ${String(err)}`);
|
|
436
|
+
failures++;
|
|
437
|
+
edges.push({
|
|
438
|
+
sourceId: frames[i].id,
|
|
439
|
+
targetId: frames[i + 1].id,
|
|
440
|
+
score: 0
|
|
441
|
+
});
|
|
442
|
+
} finally {
|
|
443
|
+
prev?.delete();
|
|
444
|
+
prev = next;
|
|
445
|
+
next = null;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const result = {
|
|
449
|
+
edges,
|
|
450
|
+
failures,
|
|
451
|
+
analysisResolution: {
|
|
452
|
+
width: imageWidth,
|
|
453
|
+
height: imageHeight
|
|
454
|
+
},
|
|
455
|
+
carry: prev ? {
|
|
456
|
+
preprocessed: preprocessed[preprocessed.length - 1],
|
|
457
|
+
features: prev
|
|
458
|
+
} : null
|
|
459
|
+
};
|
|
460
|
+
prev = null;
|
|
461
|
+
return result;
|
|
462
|
+
} finally {
|
|
463
|
+
prev?.delete();
|
|
464
|
+
next?.delete();
|
|
465
|
+
}
|
|
523
466
|
}
|
|
467
|
+
/**
|
|
468
|
+
* Analyze adjacent frame pairs to compute information gain scores (G(t)).
|
|
469
|
+
* Processes frames in batches for memory efficiency.
|
|
470
|
+
*
|
|
471
|
+
* Pipeline:
|
|
472
|
+
* 1. AKAZE Feature Set Difference
|
|
473
|
+
* 2. DBSCAN Spatial Clustering
|
|
474
|
+
* 3. Spatio-temporal IoU Tracking
|
|
475
|
+
* 4. G(t) Information Gain Scoring
|
|
476
|
+
* @param ctx - Frames, analysis options, and the progress callback for this run.
|
|
477
|
+
* @returns Adjacent scores and tracked animations in analysis coordinates.
|
|
478
|
+
* @throws Propagates runtime errors and rejects total failure of two or more pairs after cleanup.
|
|
479
|
+
*/
|
|
524
480
|
async function analyzeFrames(ctx) {
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
481
|
+
const { frames } = ctx;
|
|
482
|
+
if (frames.length < 2) return {
|
|
483
|
+
edges: [],
|
|
484
|
+
animations: [],
|
|
485
|
+
analysisResolution: {
|
|
486
|
+
width: 0,
|
|
487
|
+
height: 0
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
logger.debug(`Analyzing ${frames.length} frames in batches of ${10}`);
|
|
491
|
+
const cvLib = await ensureOpenCV();
|
|
492
|
+
const edges = [];
|
|
493
|
+
const tracker = new IoUTracker(ctx.effectiveFps ?? ctx.options.fps, ctx.options.iouThreshold, ctx.options.animationThreshold);
|
|
494
|
+
const scale = ctx.options.scale;
|
|
495
|
+
let akaze = null;
|
|
496
|
+
let carry = null;
|
|
497
|
+
let analysisResolution = {
|
|
498
|
+
width: 0,
|
|
499
|
+
height: 0
|
|
500
|
+
};
|
|
501
|
+
let failures = 0;
|
|
502
|
+
try {
|
|
503
|
+
akaze = new cvLib.AKAZE();
|
|
504
|
+
for (let i = 0; i < frames.length - 1; i += 10) {
|
|
505
|
+
const batch = [frames[i], ...frames.slice(i + 1, i + 1 + 10)];
|
|
506
|
+
const result = await analyzeBatch(cvLib, akaze, batch, carry, scale, tracker, i);
|
|
507
|
+
carry = result.carry;
|
|
508
|
+
failures += result.failures;
|
|
509
|
+
if (i === 0) analysisResolution = result.analysisResolution;
|
|
510
|
+
edges.push(...result.edges);
|
|
511
|
+
const progress = Math.min(100, (i + 10) / (frames.length - 1) * 100);
|
|
512
|
+
ctx.emitProgress(progress);
|
|
513
|
+
}
|
|
514
|
+
} finally {
|
|
515
|
+
carry?.features.delete();
|
|
516
|
+
akaze?.delete();
|
|
517
|
+
}
|
|
518
|
+
const pairs = frames.length - 1;
|
|
519
|
+
if (pairs >= 2 && failures === pairs) throw new Error(`All ${pairs} frame pairs failed analysis`);
|
|
520
|
+
const animations = tracker.flushAndGetAnimations();
|
|
521
|
+
logger.debug(`Computed ${edges.length} score edges and ${animations.length} animations`);
|
|
522
|
+
return {
|
|
523
|
+
edges,
|
|
524
|
+
animations,
|
|
525
|
+
analysisResolution
|
|
526
|
+
};
|
|
554
527
|
}
|
|
528
|
+
var OPENCV_INIT_TIMEOUT_MS, require, cvReady, IoUTracker;
|
|
529
|
+
var init_analyzer$1 = __esmMin((() => {
|
|
530
|
+
init_pipeline_defaults();
|
|
531
|
+
init_vision_tuning();
|
|
532
|
+
init_logger();
|
|
533
|
+
init_dbscan();
|
|
534
|
+
init_feature_diff();
|
|
535
|
+
init_frame_features();
|
|
536
|
+
OPENCV_INIT_TIMEOUT_MS = 3e4;
|
|
537
|
+
require = createRequire(import.meta.url);
|
|
538
|
+
cvReady = null;
|
|
539
|
+
IoUTracker = class {
|
|
540
|
+
fps;
|
|
541
|
+
iouThreshold;
|
|
542
|
+
animationThreshold;
|
|
543
|
+
regions = [];
|
|
544
|
+
extractedAnimations = [];
|
|
545
|
+
constructor(fps = 5, iouThreshold = IOU_THRESHOLD, animationThreshold = 5) {
|
|
546
|
+
this.fps = fps;
|
|
547
|
+
this.iouThreshold = iouThreshold;
|
|
548
|
+
this.animationThreshold = animationThreshold;
|
|
549
|
+
}
|
|
550
|
+
update(boxes, pairIndex) {
|
|
551
|
+
const animationIndices = /* @__PURE__ */ new Set();
|
|
552
|
+
const matched = /* @__PURE__ */ new Set();
|
|
553
|
+
for (let bi = 0; bi < boxes.length; bi++) {
|
|
554
|
+
const box = boxes[bi];
|
|
555
|
+
let bestIoU = 0;
|
|
556
|
+
let bestRegionIdx = -1;
|
|
557
|
+
for (let ri = 0; ri < this.regions.length; ri++) {
|
|
558
|
+
if (matched.has(ri)) continue;
|
|
559
|
+
const iou = computeIoU(box, this.regions[ri].box);
|
|
560
|
+
if (iou > bestIoU) {
|
|
561
|
+
bestIoU = iou;
|
|
562
|
+
bestRegionIdx = ri;
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
if (bestIoU > this.iouThreshold && bestRegionIdx !== -1) {
|
|
566
|
+
const region = this.regions[bestRegionIdx];
|
|
567
|
+
const gap = pairIndex - region.lastSeen;
|
|
568
|
+
region.box = box;
|
|
569
|
+
region.consecutiveCount++;
|
|
570
|
+
region.lastSeen = pairIndex;
|
|
571
|
+
region.weight *= Math.pow(DECAY_LAMBDA, gap);
|
|
572
|
+
matched.add(bestRegionIdx);
|
|
573
|
+
if (region.consecutiveCount >= this.animationThreshold) animationIndices.add(bi);
|
|
574
|
+
} else this.regions.push({
|
|
575
|
+
box,
|
|
576
|
+
consecutiveCount: 1,
|
|
577
|
+
firstSeen: pairIndex,
|
|
578
|
+
lastSeen: pairIndex,
|
|
579
|
+
weight: 1
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
for (let ri = 0; ri < this.regions.length; ri++) if (!matched.has(ri)) {
|
|
583
|
+
const gap = pairIndex - this.regions[ri].lastSeen;
|
|
584
|
+
this.regions[ri].weight *= Math.pow(DECAY_LAMBDA, gap);
|
|
585
|
+
}
|
|
586
|
+
for (let i = 0; i < this.regions.length; i++) {
|
|
587
|
+
const region = this.regions[i];
|
|
588
|
+
if (region.weight <= .01 && !matched.has(i)) this.collectAnimation(region);
|
|
589
|
+
}
|
|
590
|
+
this.regions = filter(this.regions, (r, i) => r.weight > .01 || matched.has(i));
|
|
591
|
+
return animationIndices;
|
|
592
|
+
}
|
|
593
|
+
collectAnimation(region) {
|
|
594
|
+
if (region.consecutiveCount >= this.animationThreshold) {
|
|
595
|
+
const durationMs = region.consecutiveCount / this.fps * 1e3;
|
|
596
|
+
this.extractedAnimations.push({
|
|
597
|
+
type: "loading_spinner",
|
|
598
|
+
boundingBox: region.box,
|
|
599
|
+
startFrameId: region.firstSeen,
|
|
600
|
+
endFrameId: region.lastSeen,
|
|
601
|
+
durationMs
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
flushAndGetAnimations() {
|
|
606
|
+
for (const region of this.regions) this.collectAnimation(region);
|
|
607
|
+
this.regions = [];
|
|
608
|
+
return this.extractedAnimations;
|
|
609
|
+
}
|
|
610
|
+
getAnimationWeight(boxIndex, boxes) {
|
|
611
|
+
if (boxIndex >= boxes.length) return 0;
|
|
612
|
+
const box = boxes[boxIndex];
|
|
613
|
+
let maxWeight = 0;
|
|
614
|
+
for (const region of this.regions) if (region.consecutiveCount >= this.animationThreshold) {
|
|
615
|
+
if (computeIoU(box, region.box) > this.iouThreshold) maxWeight = Math.max(maxWeight, region.weight);
|
|
616
|
+
}
|
|
617
|
+
return maxWeight;
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
}));
|
|
555
621
|
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
622
|
+
//#endregion
|
|
623
|
+
//#region src/core/analyzer/index.ts
|
|
624
|
+
var init_analyzer = __esmMin((() => {
|
|
625
|
+
init_analyzer$1();
|
|
626
|
+
init_dbscan();
|
|
627
|
+
}));
|
|
628
|
+
|
|
629
|
+
//#endregion
|
|
630
|
+
//#region src/core/utils/metadata/build-video-metadata.ts
|
|
631
|
+
/**
|
|
632
|
+
* Read output dimensions and build consistent video and animation metadata.
|
|
633
|
+
* JPEG finalization does not resize, so the source dimensions match the output.
|
|
634
|
+
* @param ctx Pipeline state with source duration, effective FPS and analysis-space animations.
|
|
635
|
+
* @param selected Selected frames in output order; the first candidate is the fallback.
|
|
636
|
+
* @param analysisResolution Analysis dimensions; absent or zero dimensions imply no scaling.
|
|
637
|
+
* @returns Video metadata and new output-space animations, retaining zero-based frame IDs.
|
|
638
|
+
* @throws If sharp cannot read the selected or fallback image. Empty input performs no image I/O.
|
|
639
|
+
*/
|
|
640
|
+
async function buildVideoMetadata(ctx, selected, analysisResolution) {
|
|
641
|
+
const firstFrame = selected[0] ?? ctx.frames[0];
|
|
642
|
+
const dimensions = firstFrame ? await sharp(firstFrame.extractPath).metadata() : void 0;
|
|
643
|
+
const width = dimensions?.width ?? 0;
|
|
644
|
+
const height = dimensions?.height ?? 0;
|
|
645
|
+
const sx = analysisResolution?.width ? width / analysisResolution.width : 1;
|
|
646
|
+
const sy = analysisResolution?.height ? height / analysisResolution.height : 1;
|
|
647
|
+
const lastTimestamp = ctx.frames[ctx.frames.length - 1]?.timestamp ?? 0;
|
|
648
|
+
const duration = ctx.options.mode === "frames" ? lastTimestamp : ctx.sourceDurationSec ?? lastTimestamp;
|
|
649
|
+
return {
|
|
650
|
+
video: {
|
|
651
|
+
originalDurationMs: Math.round(duration * 1e3),
|
|
652
|
+
fps: ctx.options.mode === "frames" ? 1 : ctx.effectiveFps ?? ctx.options.fps,
|
|
653
|
+
resolution: {
|
|
654
|
+
width,
|
|
655
|
+
height
|
|
656
|
+
}
|
|
657
|
+
},
|
|
658
|
+
animations: (ctx.animations ?? []).map((animation) => {
|
|
659
|
+
const box = animation.boundingBox;
|
|
660
|
+
const x = Math.max(0, Math.min(width, Math.round(box.x * sx)));
|
|
661
|
+
const y = Math.max(0, Math.min(height, Math.round(box.y * sy)));
|
|
662
|
+
return {
|
|
663
|
+
...animation,
|
|
664
|
+
boundingBox: {
|
|
665
|
+
x,
|
|
666
|
+
y,
|
|
667
|
+
width: Math.max(0, Math.min(width - x, Math.round(box.width * sx))),
|
|
668
|
+
height: Math.max(0, Math.min(height - y, Math.round(box.height * sy)))
|
|
669
|
+
}
|
|
670
|
+
};
|
|
671
|
+
})
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
var init_build_video_metadata = __esmMin((() => {}));
|
|
563
675
|
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
676
|
+
//#endregion
|
|
677
|
+
//#region src/core/constants/workspace-layout.ts
|
|
678
|
+
function getTempWorkspaceDir(sessionId) {
|
|
679
|
+
return join(TEMP_BASE_DIR, `${WORKSPACE_PREFIX}${sessionId}`);
|
|
680
|
+
}
|
|
681
|
+
var APP_NAME, WORKSPACE_PREFIX, TEMP_BASE_DIR, FRAME_OUTPUT_EXTENSION, FRAME_FILENAME_PATTERN;
|
|
682
|
+
var init_workspace_layout = __esmMin((() => {
|
|
683
|
+
APP_NAME = "scene-sieve";
|
|
684
|
+
WORKSPACE_PREFIX = `${APP_NAME}-`;
|
|
685
|
+
TEMP_BASE_DIR = tmpdir();
|
|
686
|
+
FRAME_OUTPUT_EXTENSION = ".jpg";
|
|
687
|
+
FRAME_FILENAME_PATTERN = "frame_%06d.jpg";
|
|
688
|
+
}));
|
|
689
|
+
|
|
690
|
+
//#endregion
|
|
691
|
+
//#region src/core/utils/filesystem/paths.ts
|
|
568
692
|
async function ensureDir(dirPath) {
|
|
569
|
-
|
|
693
|
+
await mkdir(dirPath, { recursive: true });
|
|
570
694
|
}
|
|
571
695
|
async function fileExists(filePath) {
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
696
|
+
try {
|
|
697
|
+
await stat(filePath);
|
|
698
|
+
return true;
|
|
699
|
+
} catch {
|
|
700
|
+
return false;
|
|
701
|
+
}
|
|
578
702
|
}
|
|
703
|
+
/**
|
|
704
|
+
* Expand leading ~ to homedir. Node's path.resolve() does not expand ~,
|
|
705
|
+
* so paths like ~/Desktop/foo depend on process.cwd() and can produce
|
|
706
|
+
* different results when run from different directories.
|
|
707
|
+
*/
|
|
579
708
|
function expandTilde(p) {
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
}
|
|
584
|
-
return p;
|
|
709
|
+
if (p === "~") return homedir();
|
|
710
|
+
if (p.startsWith("~/") || p.startsWith("~\\")) return resolve(homedir(), p.slice(2));
|
|
711
|
+
return p;
|
|
585
712
|
}
|
|
713
|
+
/**
|
|
714
|
+
* Resolve path to absolute. Expands ~ to homedir first so that the result
|
|
715
|
+
* does not depend on process.cwd().
|
|
716
|
+
*/
|
|
586
717
|
function resolveAbsolute(p) {
|
|
587
|
-
|
|
718
|
+
return resolve(expandTilde(p));
|
|
588
719
|
}
|
|
720
|
+
/**
|
|
721
|
+
* Derive default output directory name from input file path.
|
|
722
|
+
* e.g., /path/to/video.mp4 -> /path/to/video_scenes
|
|
723
|
+
*/
|
|
589
724
|
function deriveOutputPath(inputPath) {
|
|
590
|
-
|
|
591
|
-
const name = basename(inputPath, extname(inputPath));
|
|
592
|
-
return resolve(dir, `${name}_scenes`);
|
|
725
|
+
return resolve(resolve(inputPath, ".."), `${basename(inputPath, extname(inputPath))}_scenes`);
|
|
593
726
|
}
|
|
727
|
+
var init_paths = __esmMin((() => {}));
|
|
594
728
|
|
|
595
|
-
|
|
729
|
+
//#endregion
|
|
730
|
+
//#region src/core/extractor/extractor.ts
|
|
731
|
+
/**
|
|
732
|
+
* Extract frames from video/GIF using FFmpeg.
|
|
733
|
+
* @param ctx Pipeline context; records effectiveFps and sourceDurationSec for video input.
|
|
734
|
+
* @returns Extracted candidates, or the unchanged input array in frames mode.
|
|
735
|
+
* @throws When the input is missing, metadata has no video stream, or FFmpeg fails.
|
|
736
|
+
*/
|
|
596
737
|
async function extractFrames(ctx) {
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
effectiveFps = Math.min(fps, fpsCap);
|
|
629
|
-
effectiveFps = Math.max(0.5, effectiveFps);
|
|
630
|
-
logger.debug(
|
|
631
|
-
`FPS: ${fps} \u2192 effective: ${effectiveFps.toFixed(2)} (maxFrames: ${maxFrames})`
|
|
632
|
-
);
|
|
633
|
-
}
|
|
634
|
-
const frames = await extractByFps(
|
|
635
|
-
inputPath,
|
|
636
|
-
framesDir,
|
|
637
|
-
effectiveFps,
|
|
638
|
-
scale,
|
|
639
|
-
duration
|
|
640
|
-
);
|
|
641
|
-
ctx.emitProgress(100);
|
|
642
|
-
logger.debug(`Extracted ${frames.length} frames`);
|
|
643
|
-
return frames;
|
|
738
|
+
if (ctx.options.mode === "frames") {
|
|
739
|
+
ctx.effectiveFps = 1;
|
|
740
|
+
return ctx.frames;
|
|
741
|
+
}
|
|
742
|
+
const framesDir = join(ctx.workspacePath, "frames");
|
|
743
|
+
const { inputPath, fps, maxFrames, scale } = ctx.options;
|
|
744
|
+
if (!inputPath) throw new Error("inputPath is required for frame extraction");
|
|
745
|
+
if (!await fileExists(inputPath)) throw new Error(`Input file not found: ${inputPath}`);
|
|
746
|
+
const metadata = await getVideoMetadata(inputPath).catch((err) => {
|
|
747
|
+
logger.debug(`ffprobe failed: ${err.message}`);
|
|
748
|
+
return null;
|
|
749
|
+
});
|
|
750
|
+
if (!metadata || !metadata.format) throw new Error(`Could not read file metadata: ${inputPath}`);
|
|
751
|
+
const formatName = metadata.format.format_name ?? "";
|
|
752
|
+
const duration = parseFloat(metadata.format.duration ?? "0");
|
|
753
|
+
if (!(metadata.streams?.some((s) => s.codec_type === "video") ?? false)) throw new Error(`No video stream found in file: ${inputPath} (detected format: ${formatName})`);
|
|
754
|
+
logger.debug(`Detected format: ${formatName} (Duration: ${duration.toFixed(1)}s), path: ${inputPath}`);
|
|
755
|
+
await ensureDir(framesDir);
|
|
756
|
+
const frameLimit = Math.max(2, maxFrames);
|
|
757
|
+
let effectiveFps = fps;
|
|
758
|
+
if (duration > 0) {
|
|
759
|
+
const fpsCap = frameLimit / duration;
|
|
760
|
+
effectiveFps = Math.min(fps, fpsCap);
|
|
761
|
+
logger.debug(`FPS: ${fps} → effective: ${effectiveFps.toFixed(2)} (maxFrames: ${maxFrames})`);
|
|
762
|
+
}
|
|
763
|
+
ctx.effectiveFps = effectiveFps;
|
|
764
|
+
ctx.sourceDurationSec = duration;
|
|
765
|
+
const frames = await extractByFps(inputPath, framesDir, effectiveFps, scale, frameLimit);
|
|
766
|
+
ctx.emitProgress(100);
|
|
767
|
+
logger.debug(`Extracted ${frames.length} frames`);
|
|
768
|
+
return frames;
|
|
644
769
|
}
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
770
|
+
/**
|
|
771
|
+
* Write scaled JPEG candidates through the bundled FFmpeg runtime.
|
|
772
|
+
* @param inputPath Readable video input.
|
|
773
|
+
* @param outputDir Existing frame directory.
|
|
774
|
+
* @param fps Positive effective sampling frequency.
|
|
775
|
+
* @param scale Output image height.
|
|
776
|
+
* @param frameLimit Maximum number of output frames.
|
|
777
|
+
* @returns Candidates with local output-grid timestamps; rejects on extraction failure.
|
|
778
|
+
*/
|
|
779
|
+
async function extractByFps(inputPath, outputDir, fps, scale, frameLimit) {
|
|
780
|
+
const outputPattern = join(outputDir, FRAME_FILENAME_PATTERN);
|
|
781
|
+
await execa(ffmpegPath, [
|
|
782
|
+
"-i",
|
|
783
|
+
inputPath,
|
|
784
|
+
"-vf",
|
|
785
|
+
`fps=${fps},scale=-1:${scale}`,
|
|
786
|
+
"-q:v",
|
|
787
|
+
"2",
|
|
788
|
+
"-frames:v",
|
|
789
|
+
String(frameLimit),
|
|
790
|
+
outputPattern
|
|
791
|
+
]);
|
|
792
|
+
return buildFrameList(outputDir, fps);
|
|
657
793
|
}
|
|
658
794
|
async function getVideoMetadata(inputPath) {
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
795
|
+
const { stdout } = await execa(path, [
|
|
796
|
+
"-v",
|
|
797
|
+
"quiet",
|
|
798
|
+
"-print_format",
|
|
799
|
+
"json",
|
|
800
|
+
"-show_format",
|
|
801
|
+
"-show_streams",
|
|
802
|
+
inputPath
|
|
803
|
+
]);
|
|
804
|
+
return JSON.parse(stdout);
|
|
669
805
|
}
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
806
|
+
/**
|
|
807
|
+
* Read sorted JPEG paths and attach local output-grid times.
|
|
808
|
+
* @param framesDir Extracted frame directory; filesystem errors propagate.
|
|
809
|
+
* @param effectiveFps Positive frequency used by the fps filter.
|
|
810
|
+
* @returns Zero-based candidates without a segment seek offset.
|
|
811
|
+
*/
|
|
812
|
+
async function buildFrameList(framesDir, effectiveFps) {
|
|
813
|
+
const jpgFiles = filter(await readdir(framesDir), (f) => f.endsWith(".jpg")).sort();
|
|
814
|
+
if (jpgFiles.length === 0) return [];
|
|
815
|
+
return map(jpgFiles, (file, index) => ({
|
|
816
|
+
id: index,
|
|
817
|
+
timestamp: index / effectiveFps,
|
|
818
|
+
extractPath: join(framesDir, file)
|
|
819
|
+
}));
|
|
681
820
|
}
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
821
|
+
/**
|
|
822
|
+
* Extract frames from a specific time range of a video using FFmpeg.
|
|
823
|
+
* Uses input seeking (-ss before -i) for fast seek + -t for duration.
|
|
824
|
+
*
|
|
825
|
+
* @param inputPath - Path to the video file
|
|
826
|
+
* @param outputDir - Directory to write extracted frames
|
|
827
|
+
* @param fps - Frames per second for extraction
|
|
828
|
+
* @param scale - Height scale for vision analysis
|
|
829
|
+
* @param startTime - Start time in seconds
|
|
830
|
+
* @param duration - Duration in seconds to extract
|
|
831
|
+
* @param frameLimit - Positive output limit; defaults to the range's grid capacity
|
|
832
|
+
* @returns Array of FrameNode with segment-local timestamps (starting from 0)
|
|
833
|
+
*/
|
|
834
|
+
async function extractFramesForRange(inputPath, outputDir, fps, scale, startTime, duration, frameLimit = Math.ceil(duration * fps)) {
|
|
835
|
+
const outputPattern = join(outputDir, FRAME_FILENAME_PATTERN);
|
|
836
|
+
await execa(ffmpegPath, [
|
|
837
|
+
"-ss",
|
|
838
|
+
String(startTime),
|
|
839
|
+
"-i",
|
|
840
|
+
inputPath,
|
|
841
|
+
"-t",
|
|
842
|
+
String(duration),
|
|
843
|
+
"-vf",
|
|
844
|
+
`fps=${fps},scale=-1:${scale}`,
|
|
845
|
+
"-q:v",
|
|
846
|
+
"2",
|
|
847
|
+
"-frames:v",
|
|
848
|
+
String(frameLimit),
|
|
849
|
+
outputPattern
|
|
850
|
+
]);
|
|
851
|
+
return buildFrameList(outputDir, fps);
|
|
698
852
|
}
|
|
853
|
+
var init_extractor$1 = __esmMin((() => {
|
|
854
|
+
init_workspace_layout();
|
|
855
|
+
init_logger();
|
|
856
|
+
init_paths();
|
|
857
|
+
}));
|
|
699
858
|
|
|
700
|
-
|
|
701
|
-
|
|
859
|
+
//#endregion
|
|
860
|
+
//#region src/core/extractor/index.ts
|
|
861
|
+
var init_extractor = __esmMin((() => {
|
|
862
|
+
init_extractor$1();
|
|
863
|
+
}));
|
|
702
864
|
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
865
|
+
//#endregion
|
|
866
|
+
//#region src/core/input-resolver/validation/validate-options.ts
|
|
867
|
+
/**
|
|
868
|
+
* Reject invalid numeric options before defaults or pipeline effects are applied.
|
|
869
|
+
* @param options - Supplied options; omitted numeric fields use pipeline defaults.
|
|
870
|
+
* @returns Nothing when all supplied numeric fields satisfy their contracts.
|
|
871
|
+
* @throws An input error naming the invalid option and its received value.
|
|
872
|
+
*/
|
|
873
|
+
function validateOptions(options) {
|
|
874
|
+
for (const [name, min, max, integer, exclusiveMin, requirement] of [
|
|
875
|
+
[
|
|
876
|
+
"count",
|
|
877
|
+
1,
|
|
878
|
+
Infinity,
|
|
879
|
+
true,
|
|
880
|
+
false,
|
|
881
|
+
"an integer >= 1"
|
|
882
|
+
],
|
|
883
|
+
[
|
|
884
|
+
"threshold",
|
|
885
|
+
0,
|
|
886
|
+
1,
|
|
887
|
+
false,
|
|
888
|
+
true,
|
|
889
|
+
"in range (0, 1] and finite"
|
|
890
|
+
],
|
|
891
|
+
[
|
|
892
|
+
"fps",
|
|
893
|
+
0,
|
|
894
|
+
Infinity,
|
|
895
|
+
false,
|
|
896
|
+
true,
|
|
897
|
+
"finite and > 0"
|
|
898
|
+
],
|
|
899
|
+
[
|
|
900
|
+
"maxFrames",
|
|
901
|
+
2,
|
|
902
|
+
Infinity,
|
|
903
|
+
true,
|
|
904
|
+
false,
|
|
905
|
+
"an integer >= 2"
|
|
906
|
+
],
|
|
907
|
+
[
|
|
908
|
+
"scale",
|
|
909
|
+
16,
|
|
910
|
+
Infinity,
|
|
911
|
+
true,
|
|
912
|
+
false,
|
|
913
|
+
"an integer >= 16"
|
|
914
|
+
],
|
|
915
|
+
[
|
|
916
|
+
"quality",
|
|
917
|
+
1,
|
|
918
|
+
100,
|
|
919
|
+
true,
|
|
920
|
+
false,
|
|
921
|
+
"an integer in range [1, 100]"
|
|
922
|
+
],
|
|
923
|
+
[
|
|
924
|
+
"iouThreshold",
|
|
925
|
+
0,
|
|
926
|
+
1,
|
|
927
|
+
false,
|
|
928
|
+
false,
|
|
929
|
+
"finite and in range [0, 1]"
|
|
930
|
+
],
|
|
931
|
+
[
|
|
932
|
+
"animationThreshold",
|
|
933
|
+
1,
|
|
934
|
+
Infinity,
|
|
935
|
+
true,
|
|
936
|
+
false,
|
|
937
|
+
"an integer >= 1"
|
|
938
|
+
],
|
|
939
|
+
[
|
|
940
|
+
"maxSegmentDuration",
|
|
941
|
+
0,
|
|
942
|
+
Infinity,
|
|
943
|
+
false,
|
|
944
|
+
true,
|
|
945
|
+
"finite and > 0"
|
|
946
|
+
],
|
|
947
|
+
[
|
|
948
|
+
"concurrency",
|
|
949
|
+
1,
|
|
950
|
+
Infinity,
|
|
951
|
+
true,
|
|
952
|
+
false,
|
|
953
|
+
"an integer >= 1"
|
|
954
|
+
]
|
|
955
|
+
]) {
|
|
956
|
+
const value = options[name];
|
|
957
|
+
if (value === void 0) continue;
|
|
958
|
+
if (!Number.isFinite(value) || integer && !Number.isInteger(value) || (exclusiveMin ? value <= min : value < min) || value > max) throw new Error(`${name} must be ${requirement}, received: ${value}`);
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
var init_validate_options = __esmMin((() => {}));
|
|
962
|
+
|
|
963
|
+
//#endregion
|
|
964
|
+
//#region src/core/workspace/workspace.ts
|
|
708
965
|
async function createWorkspace(sessionId) {
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
966
|
+
const workspacePath = getTempWorkspaceDir(sessionId);
|
|
967
|
+
await ensureDir(join(workspacePath, "frames"));
|
|
968
|
+
await ensureDir(join(workspacePath, "output"));
|
|
969
|
+
return workspacePath;
|
|
713
970
|
}
|
|
714
971
|
async function finalizeOutput(ctx, selectedFrames) {
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
await rm(outputPath, { recursive: true, force: true });
|
|
759
|
-
await rename(stagingDir, outputPath);
|
|
760
|
-
return outputFiles;
|
|
972
|
+
const stagingDir = join(ctx.workspacePath, "output");
|
|
973
|
+
const outputPath = ctx.options.outputPath;
|
|
974
|
+
const quality = ctx.options.quality;
|
|
975
|
+
const outputFiles = [];
|
|
976
|
+
const framesMetadata = [];
|
|
977
|
+
const totalFramesCount = ctx.frames.length;
|
|
978
|
+
const padding = Math.max(4, String(totalFramesCount).length);
|
|
979
|
+
for (let i = 0; i < selectedFrames.length; i++) {
|
|
980
|
+
const frame = selectedFrames[i];
|
|
981
|
+
const fileName = `frame_${String(frame.id + 1).padStart(padding, "0")}.jpg`;
|
|
982
|
+
const destPath = join(stagingDir, fileName);
|
|
983
|
+
await sharp(frame.extractPath).jpeg({
|
|
984
|
+
quality,
|
|
985
|
+
mozjpeg: true
|
|
986
|
+
}).toFile(destPath);
|
|
987
|
+
outputFiles.push(join(outputPath, fileName));
|
|
988
|
+
framesMetadata.push({
|
|
989
|
+
step: i + 1,
|
|
990
|
+
fileName,
|
|
991
|
+
frameId: frame.id + 1,
|
|
992
|
+
timestampMs: Math.round(frame.timestamp * 1e3)
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
const { video, animations } = await buildVideoMetadata(ctx, selectedFrames, ctx.analysisResolution);
|
|
996
|
+
const metadata = {
|
|
997
|
+
video,
|
|
998
|
+
frames: framesMetadata,
|
|
999
|
+
animations: map(animations, (anim) => ({
|
|
1000
|
+
...anim,
|
|
1001
|
+
startFrameId: anim.startFrameId + 1,
|
|
1002
|
+
endFrameId: anim.endFrameId + 1,
|
|
1003
|
+
durationMs: Math.round(anim.durationMs)
|
|
1004
|
+
}))
|
|
1005
|
+
};
|
|
1006
|
+
await writeFile(join(stagingDir, ".metadata.json"), JSON.stringify(metadata, null, 2));
|
|
1007
|
+
outputFiles.push(join(outputPath, ".metadata.json"));
|
|
1008
|
+
await ensureDir(join(outputPath, ".."));
|
|
1009
|
+
await rm(outputPath, {
|
|
1010
|
+
recursive: true,
|
|
1011
|
+
force: true
|
|
1012
|
+
});
|
|
1013
|
+
await rename(stagingDir, outputPath);
|
|
1014
|
+
return outputFiles;
|
|
761
1015
|
}
|
|
762
1016
|
async function createSegmentWorkspace(parentWorkspacePath, segmentIndex) {
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
String(segmentIndex)
|
|
767
|
-
);
|
|
768
|
-
await ensureDir(join3(segmentPath, "frames"));
|
|
769
|
-
return segmentPath;
|
|
1017
|
+
const segmentPath = join(parentWorkspacePath, "segments", String(segmentIndex));
|
|
1018
|
+
await ensureDir(join(segmentPath, "frames"));
|
|
1019
|
+
return segmentPath;
|
|
770
1020
|
}
|
|
771
1021
|
async function cleanupWorkspace(workspacePath) {
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
1022
|
+
if (!workspacePath) return;
|
|
1023
|
+
try {
|
|
1024
|
+
await rm(workspacePath, {
|
|
1025
|
+
recursive: true,
|
|
1026
|
+
force: true
|
|
1027
|
+
});
|
|
1028
|
+
} catch {}
|
|
777
1029
|
}
|
|
778
|
-
|
|
1030
|
+
/**
|
|
1031
|
+
* Write a video buffer to a temp file in the workspace and return the path.
|
|
1032
|
+
* Used by 'buffer' input mode.
|
|
1033
|
+
*/
|
|
779
1034
|
async function writeInputBuffer(buffer, workspacePath) {
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
1035
|
+
const inputDir = join(workspacePath, "input");
|
|
1036
|
+
await ensureDir(inputDir);
|
|
1037
|
+
const tempPath = join(inputDir, "input.mp4");
|
|
1038
|
+
await writeFile(tempPath, buffer);
|
|
1039
|
+
return tempPath;
|
|
785
1040
|
}
|
|
1041
|
+
/**
|
|
1042
|
+
* Write an array of frame Buffers as JPG files and return FrameNode[].
|
|
1043
|
+
* Used by 'frames' input mode.
|
|
1044
|
+
*/
|
|
786
1045
|
async function writeInputFrames(frames, workspacePath) {
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
1046
|
+
const framesDir = join(workspacePath, "frames");
|
|
1047
|
+
await ensureDir(framesDir);
|
|
1048
|
+
const frameNodes = [];
|
|
1049
|
+
for (let i = 0; i < frames.length; i++) {
|
|
1050
|
+
const extractPath = join(framesDir, `frame_${String(i).padStart(6, "0")}${FRAME_OUTPUT_EXTENSION}`);
|
|
1051
|
+
await writeFile(extractPath, frames[i]);
|
|
1052
|
+
frameNodes.push({
|
|
1053
|
+
id: i,
|
|
1054
|
+
timestamp: i,
|
|
1055
|
+
extractPath
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
return frameNodes;
|
|
797
1059
|
}
|
|
1060
|
+
/**
|
|
1061
|
+
* Read selected FrameNode files as Buffers with JPEG compression.
|
|
1062
|
+
* Used to return output buffers in 'buffer' and 'frames' modes.
|
|
1063
|
+
*/
|
|
798
1064
|
async function readFramesAsBuffers(frameNodes, quality) {
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
)
|
|
804
|
-
);
|
|
1065
|
+
return Promise.all(map(frameNodes, (f) => sharp(f.extractPath).jpeg({
|
|
1066
|
+
quality,
|
|
1067
|
+
mozjpeg: true
|
|
1068
|
+
}).toBuffer()));
|
|
805
1069
|
}
|
|
1070
|
+
var init_workspace$1 = __esmMin((() => {
|
|
1071
|
+
init_workspace_layout();
|
|
1072
|
+
init_paths();
|
|
1073
|
+
init_build_video_metadata();
|
|
1074
|
+
}));
|
|
1075
|
+
|
|
1076
|
+
//#endregion
|
|
1077
|
+
//#region src/core/workspace/index.ts
|
|
1078
|
+
var init_workspace = __esmMin((() => {
|
|
1079
|
+
init_workspace$1();
|
|
1080
|
+
}));
|
|
806
1081
|
|
|
807
|
-
|
|
1082
|
+
//#endregion
|
|
1083
|
+
//#region src/core/input-resolver/input-resolver.ts
|
|
1084
|
+
/**
|
|
1085
|
+
* Validate supplied options and resolve defaults and paths for the pipeline.
|
|
1086
|
+
* @param options - Mode-specific input and optional numeric settings.
|
|
1087
|
+
* @returns Complete pipeline settings with absolute file input paths.
|
|
1088
|
+
* @throws An input error if a supplied numeric setting is invalid.
|
|
1089
|
+
*/
|
|
808
1090
|
function resolveOptions(options) {
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
animationThreshold: options.animationThreshold ?? ANIMATION_FRAME_THRESHOLD,
|
|
832
|
-
debug: options.debug ?? false,
|
|
833
|
-
maxSegmentDuration: options.maxSegmentDuration ?? DEFAULT_MAX_SEGMENT_DURATION,
|
|
834
|
-
concurrency: options.concurrency ?? DEFAULT_SEGMENT_CONCURRENCY
|
|
835
|
-
};
|
|
1091
|
+
validateOptions(options);
|
|
1092
|
+
const mode = options.mode;
|
|
1093
|
+
const inputPath = mode === "file" ? resolveAbsolute(options.inputPath) : void 0;
|
|
1094
|
+
const outputPath = options.outputPath ?? (inputPath ? deriveOutputPath(inputPath) : join(process.cwd(), "scene-sieve-output"));
|
|
1095
|
+
const threshold = options.threshold ?? .5;
|
|
1096
|
+
return {
|
|
1097
|
+
mode,
|
|
1098
|
+
inputPath,
|
|
1099
|
+
count: options.count ?? 20,
|
|
1100
|
+
threshold,
|
|
1101
|
+
pruneMode: "threshold-with-cap",
|
|
1102
|
+
outputPath,
|
|
1103
|
+
fps: options.fps ?? 5,
|
|
1104
|
+
maxFrames: options.maxFrames ?? 300,
|
|
1105
|
+
scale: options.scale ?? 720,
|
|
1106
|
+
quality: options.quality ?? 80,
|
|
1107
|
+
iouThreshold: options.iouThreshold ?? .9,
|
|
1108
|
+
animationThreshold: options.animationThreshold ?? 5,
|
|
1109
|
+
debug: options.debug ?? false,
|
|
1110
|
+
maxSegmentDuration: options.maxSegmentDuration ?? 300,
|
|
1111
|
+
concurrency: options.concurrency ?? 2
|
|
1112
|
+
};
|
|
836
1113
|
}
|
|
1114
|
+
/**
|
|
1115
|
+
* Resolve the input source to a list of FrameNode[].
|
|
1116
|
+
*
|
|
1117
|
+
* - 'file' mode: validate file exists and delegate to extractor (caller's responsibility)
|
|
1118
|
+
* - 'buffer' mode: write buffer as temp video file, return path via FrameNode trick (empty list)
|
|
1119
|
+
* - 'frames' mode: write frame buffers as JPGs, return FrameNode[]
|
|
1120
|
+
* @param options - Input source; encoded frames must have matching dimensions.
|
|
1121
|
+
* @param workspacePath - Workspace receiving temporary input files.
|
|
1122
|
+
* @returns Frame nodes or a resolved video path for extraction.
|
|
1123
|
+
* @throws Propagates metadata or write errors and rejects mismatched frame sizes.
|
|
1124
|
+
*/
|
|
837
1125
|
async function resolveInput(options, workspacePath) {
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
1126
|
+
if (options.mode === "file") return {
|
|
1127
|
+
frames: [],
|
|
1128
|
+
resolvedInputPath: resolveAbsolute(options.inputPath)
|
|
1129
|
+
};
|
|
1130
|
+
if (options.mode === "buffer") return {
|
|
1131
|
+
frames: [],
|
|
1132
|
+
resolvedInputPath: await writeInputBuffer(options.inputBuffer, workspacePath)
|
|
1133
|
+
};
|
|
1134
|
+
if (options.mode === "frames") {
|
|
1135
|
+
let dimensions;
|
|
1136
|
+
for (const buffer of options.inputFrames) {
|
|
1137
|
+
const { width, height } = await sharp(buffer).metadata();
|
|
1138
|
+
if (dimensions && (width !== dimensions.width || height !== dimensions.height)) throw new Error(`inputFrames must be the same size (${dimensions.width}x${dimensions.height}), received: ${width}x${height}`);
|
|
1139
|
+
dimensions = {
|
|
1140
|
+
width,
|
|
1141
|
+
height
|
|
1142
|
+
};
|
|
1143
|
+
}
|
|
1144
|
+
return { frames: await writeInputFrames(options.inputFrames, workspacePath) };
|
|
1145
|
+
}
|
|
1146
|
+
throw new Error(`Unsupported input mode: ${options.mode}`);
|
|
856
1147
|
}
|
|
1148
|
+
var init_input_resolver$1 = __esmMin((() => {
|
|
1149
|
+
init_pipeline_defaults();
|
|
1150
|
+
init_paths();
|
|
1151
|
+
init_validate_options();
|
|
1152
|
+
init_workspace();
|
|
1153
|
+
}));
|
|
857
1154
|
|
|
858
|
-
|
|
859
|
-
|
|
1155
|
+
//#endregion
|
|
1156
|
+
//#region src/core/input-resolver/index.ts
|
|
1157
|
+
var init_input_resolver = __esmMin((() => {
|
|
1158
|
+
init_input_resolver$1();
|
|
1159
|
+
}));
|
|
860
1160
|
|
|
861
|
-
|
|
862
|
-
|
|
1161
|
+
//#endregion
|
|
1162
|
+
//#region src/core/pruner/scoring/normalize-scores.ts
|
|
1163
|
+
/**
|
|
1164
|
+
* Find the first position whose score is at least the requested value.
|
|
1165
|
+
* @param sorted - Finite positive scores sorted in ascending order.
|
|
1166
|
+
* @param value - A finite positive score present in sorted.
|
|
1167
|
+
* @returns The first matching rank, including the first position of any tie.
|
|
1168
|
+
*/
|
|
1169
|
+
function lowerBound(sorted, value) {
|
|
1170
|
+
let low = 0;
|
|
1171
|
+
let high = sorted.length;
|
|
1172
|
+
while (low < high) {
|
|
1173
|
+
const mid = Math.floor((low + high) / 2);
|
|
1174
|
+
if (sorted[mid] < value) low = mid + 1;
|
|
1175
|
+
else high = mid;
|
|
1176
|
+
}
|
|
1177
|
+
return low;
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* Normalize raw scores to [0, 1] range via Robust Hybrid Normalization.
|
|
1181
|
+
*
|
|
1182
|
+
* This model combines two mathematical approaches to provide a stable "relative" threshold:
|
|
1183
|
+
*
|
|
1184
|
+
* 1. Logistic-Robust-Z (Intensity):
|
|
1185
|
+
* Calculates Z-scores using Median and Median Absolute Deviation (MAD).
|
|
1186
|
+
* Maps these to a sigmoid (logistic) curve. This suppresses noise (scores near median)
|
|
1187
|
+
* and highlights significant signals (outliers) without letting extreme outliers
|
|
1188
|
+
* crush other meaningful transitions.
|
|
1189
|
+
*
|
|
1190
|
+
* 2. CDF / Percentile Rank (Relative Position):
|
|
1191
|
+
* Maps each score to its percentile rank in the sequence. This ensures that 't'
|
|
1192
|
+
* always has a consistent meaning as a "relative rank" regardless of absolute values.
|
|
1193
|
+
*
|
|
1194
|
+
* The final score is a weighted sum (NORMALIZATION_ALPHA) of both.
|
|
1195
|
+
*
|
|
1196
|
+
* @param items - Array of items with scores to normalize
|
|
1197
|
+
* @returns normalized scores array (same length as input)
|
|
1198
|
+
*/
|
|
863
1199
|
function normalizeScores(items) {
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
});
|
|
891
|
-
const cdf = map4(safeScores, (s) => {
|
|
892
|
-
if (s <= 0) return 0;
|
|
893
|
-
const rank = sorted.findIndex((v) => v >= s);
|
|
894
|
-
return rank / sorted.length;
|
|
895
|
-
});
|
|
896
|
-
return map4(
|
|
897
|
-
logisticZ,
|
|
898
|
-
(z, i) => z * (1 - NORMALIZATION_ALPHA) + cdf[i] * NORMALIZATION_ALPHA
|
|
899
|
-
);
|
|
1200
|
+
if (items.length === 0) return [];
|
|
1201
|
+
const safeScores = map(items, (e) => Number.isFinite(e.score) && e.score > 0 ? e.score : 0);
|
|
1202
|
+
const positiveScores = filter(safeScores, (s) => s > 0);
|
|
1203
|
+
if (positiveScores.length === 0) return safeScores;
|
|
1204
|
+
const sorted = [...positiveScores].sort((a, b) => a - b);
|
|
1205
|
+
if (positiveScores.length <= 10) {
|
|
1206
|
+
const min = sorted[0];
|
|
1207
|
+
const max = sorted[sorted.length - 1];
|
|
1208
|
+
if (max === min) return map(safeScores, (s) => s > 0 ? 1 : 0);
|
|
1209
|
+
return map(safeScores, (s) => s <= 0 ? 0 : Math.max(0, Math.min((s - min) / (max - min), 1)));
|
|
1210
|
+
}
|
|
1211
|
+
const median = sorted[Math.floor(sorted.length / 2)];
|
|
1212
|
+
const absoluteDiffs = map(positiveScores, (v) => Math.abs(v - median));
|
|
1213
|
+
const mad = [...absoluteDiffs].sort((a, b) => a - b)[Math.floor(absoluteDiffs.length / 2)];
|
|
1214
|
+
const scale = mad === 0 ? median : mad * NORMALIZATION_MAD_COEFFICIENT;
|
|
1215
|
+
const logisticZ = map(safeScores, (s) => {
|
|
1216
|
+
if (s <= 0) return 0;
|
|
1217
|
+
if (scale === 0) return 1;
|
|
1218
|
+
const z = (s - median) / scale;
|
|
1219
|
+
return 1 / (1 + Math.exp(-3 * z));
|
|
1220
|
+
});
|
|
1221
|
+
const cdf = map(safeScores, (s) => {
|
|
1222
|
+
if (s <= 0) return 0;
|
|
1223
|
+
return lowerBound(sorted, s) / sorted.length;
|
|
1224
|
+
});
|
|
1225
|
+
return map(logisticZ, (z, i) => z * (1 - NORMALIZATION_ALPHA) + cdf[i] * NORMALIZATION_ALPHA);
|
|
900
1226
|
}
|
|
1227
|
+
var NORMALIZATION_ALPHA, NORMALIZATION_MAD_COEFFICIENT, NORMALIZATION_MIN_SAMPLE_SIZE;
|
|
1228
|
+
var init_normalize_scores = __esmMin((() => {
|
|
1229
|
+
NORMALIZATION_ALPHA = .4;
|
|
1230
|
+
NORMALIZATION_MAD_COEFFICIENT = 1.4826;
|
|
1231
|
+
NORMALIZATION_MIN_SAMPLE_SIZE = 10;
|
|
1232
|
+
}));
|
|
901
1233
|
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
1234
|
+
//#endregion
|
|
1235
|
+
//#region src/core/pruner/heap/min-heap.ts
|
|
1236
|
+
var MinHeap;
|
|
1237
|
+
var init_min_heap = __esmMin((() => {
|
|
1238
|
+
MinHeap = class {
|
|
1239
|
+
h = [];
|
|
1240
|
+
get size() {
|
|
1241
|
+
return this.h.length;
|
|
1242
|
+
}
|
|
1243
|
+
push(entry) {
|
|
1244
|
+
this.h.push(entry);
|
|
1245
|
+
this.siftUp(this.h.length - 1);
|
|
1246
|
+
}
|
|
1247
|
+
pop() {
|
|
1248
|
+
const n = this.h.length;
|
|
1249
|
+
if (n === 0) return void 0;
|
|
1250
|
+
const top = this.h[0];
|
|
1251
|
+
const last = this.h.pop();
|
|
1252
|
+
if (n > 1) {
|
|
1253
|
+
this.h[0] = last;
|
|
1254
|
+
this.siftDown(0);
|
|
1255
|
+
}
|
|
1256
|
+
return top;
|
|
1257
|
+
}
|
|
1258
|
+
siftUp(i) {
|
|
1259
|
+
while (i > 0) {
|
|
1260
|
+
const p = i - 1 >> 1;
|
|
1261
|
+
if (this.h[p].score <= this.h[i].score) break;
|
|
1262
|
+
[this.h[p], this.h[i]] = [this.h[i], this.h[p]];
|
|
1263
|
+
i = p;
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
siftDown(i) {
|
|
1267
|
+
const n = this.h.length;
|
|
1268
|
+
for (;;) {
|
|
1269
|
+
let m = i;
|
|
1270
|
+
const l = 2 * i + 1;
|
|
1271
|
+
const r = 2 * i + 2;
|
|
1272
|
+
if (l < n && this.h[l].score < this.h[m].score) m = l;
|
|
1273
|
+
if (r < n && this.h[r].score < this.h[m].score) m = r;
|
|
1274
|
+
if (m === i) break;
|
|
1275
|
+
[this.h[m], this.h[i]] = [this.h[i], this.h[m]];
|
|
1276
|
+
i = m;
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
};
|
|
1280
|
+
}));
|
|
945
1281
|
|
|
946
|
-
|
|
1282
|
+
//#endregion
|
|
1283
|
+
//#region src/core/pruner/pruner.ts
|
|
1284
|
+
/**
|
|
1285
|
+
* Edge-aware greedy merge with re-linking — O(N log N).
|
|
1286
|
+
*
|
|
1287
|
+
* 1. Build a doubly-linked list of frames
|
|
1288
|
+
* 2. Insert all edges into a min-heap
|
|
1289
|
+
* 3. Pop the lowest-score edge (most similar pair)
|
|
1290
|
+
* 4. Remove the later frame (tgtId), re-link neighbors
|
|
1291
|
+
* 5. Push synthetic edge with score = max(left, right)
|
|
1292
|
+
* 6. Repeat until surviving count === targetCount
|
|
1293
|
+
* 7. First and last frames are never removed (boundary preservation)
|
|
1294
|
+
*
|
|
1295
|
+
* Stale heap entries (involving removed frames) are lazily skipped on pop.
|
|
1296
|
+
*/
|
|
947
1297
|
function pruneTo(graph, frames, targetCount) {
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
1298
|
+
if (frames.length <= targetCount) return new Set(map(frames, (f) => f.id));
|
|
1299
|
+
const prev = /* @__PURE__ */ new Map();
|
|
1300
|
+
const next = /* @__PURE__ */ new Map();
|
|
1301
|
+
for (let i = 0; i < frames.length; i++) {
|
|
1302
|
+
if (i > 0) prev.set(frames[i].id, frames[i - 1].id);
|
|
1303
|
+
if (i < frames.length - 1) next.set(frames[i].id, frames[i + 1].id);
|
|
1304
|
+
}
|
|
1305
|
+
const edgeScore = /* @__PURE__ */ new Map();
|
|
1306
|
+
const heap = new MinHeap();
|
|
1307
|
+
for (const edge of graph) {
|
|
1308
|
+
edgeScore.set(`${edge.sourceId}:${edge.targetId}`, edge.score);
|
|
1309
|
+
heap.push({
|
|
1310
|
+
score: edge.score,
|
|
1311
|
+
srcId: edge.sourceId,
|
|
1312
|
+
tgtId: edge.targetId
|
|
1313
|
+
});
|
|
1314
|
+
}
|
|
1315
|
+
const surviving = new Set(map(frames, (f) => f.id));
|
|
1316
|
+
const firstId = frames[0].id;
|
|
1317
|
+
const lastId = frames[frames.length - 1].id;
|
|
1318
|
+
while (surviving.size > targetCount && heap.size > 0) {
|
|
1319
|
+
const entry = heap.pop();
|
|
1320
|
+
if (!surviving.has(entry.srcId) || !surviving.has(entry.tgtId)) continue;
|
|
1321
|
+
const key = `${entry.srcId}:${entry.tgtId}`;
|
|
1322
|
+
if (edgeScore.get(key) !== entry.score) continue;
|
|
1323
|
+
if (entry.tgtId === firstId || entry.tgtId === lastId) continue;
|
|
1324
|
+
surviving.delete(entry.tgtId);
|
|
1325
|
+
edgeScore.delete(key);
|
|
1326
|
+
const tgtNext = next.get(entry.tgtId);
|
|
1327
|
+
if (tgtNext !== void 0) {
|
|
1328
|
+
const rightKey = `${entry.tgtId}:${tgtNext}`;
|
|
1329
|
+
const rightScore = edgeScore.get(rightKey) ?? 0;
|
|
1330
|
+
edgeScore.delete(rightKey);
|
|
1331
|
+
const newScore = Math.max(entry.score, rightScore);
|
|
1332
|
+
edgeScore.set(`${entry.srcId}:${tgtNext}`, newScore);
|
|
1333
|
+
heap.push({
|
|
1334
|
+
score: newScore,
|
|
1335
|
+
srcId: entry.srcId,
|
|
1336
|
+
tgtId: tgtNext
|
|
1337
|
+
});
|
|
1338
|
+
next.set(entry.srcId, tgtNext);
|
|
1339
|
+
prev.set(tgtNext, entry.srcId);
|
|
1340
|
+
} else next.delete(entry.srcId);
|
|
1341
|
+
prev.delete(entry.tgtId);
|
|
1342
|
+
next.delete(entry.tgtId);
|
|
1343
|
+
}
|
|
1344
|
+
return surviving;
|
|
995
1345
|
}
|
|
1346
|
+
/**
|
|
1347
|
+
* Non-Maximum Suppression (NMS) for consecutive edge runs.
|
|
1348
|
+
*
|
|
1349
|
+
* Consecutive edges share overlapping frames (edge i: frame i->i+1,
|
|
1350
|
+
* edge i+1: frame i+1->i+2), so consecutive passing edges indicate
|
|
1351
|
+
* the same visual transition region. This function groups consecutive
|
|
1352
|
+
* passing edge indices into "runs" and keeps all distinct peaks per run.
|
|
1353
|
+
*
|
|
1354
|
+
* Multi-peak detection: within each run, strict local maxima (score higher
|
|
1355
|
+
* than both neighbors) are identified. Each local maximum represents a
|
|
1356
|
+
* distinct visual transition. If no strict local maxima exist (plateau or
|
|
1357
|
+
* monotonic sequence), the global peak of the run is selected as fallback.
|
|
1358
|
+
*
|
|
1359
|
+
* Single-element runs are unaffected (isolated transitions preserved).
|
|
1360
|
+
*
|
|
1361
|
+
* @param graph - full ScoreEdge array (for targetId lookup)
|
|
1362
|
+
* @param passingIndices - edge indices that passed threshold filtering (sorted ascending)
|
|
1363
|
+
* @param normalizedScores - normalized score array (same length as graph)
|
|
1364
|
+
* @returns Set of targetIds to add to surviving set (one or more per run)
|
|
1365
|
+
*/
|
|
996
1366
|
function suppressConsecutiveRuns(graph, passingIndices, normalizedScores) {
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
const idx = passingIndices[j];
|
|
1026
|
-
if (normalizedScores[idx] > normalizedScores[peakIdx]) {
|
|
1027
|
-
peakIdx = idx;
|
|
1028
|
-
}
|
|
1029
|
-
}
|
|
1030
|
-
result.add(graph[peakIdx].targetId);
|
|
1031
|
-
}
|
|
1032
|
-
}
|
|
1033
|
-
runStart = runEnd + 1;
|
|
1034
|
-
}
|
|
1035
|
-
return result;
|
|
1367
|
+
const result = /* @__PURE__ */ new Set();
|
|
1368
|
+
let runStart = 0;
|
|
1369
|
+
while (runStart < passingIndices.length) {
|
|
1370
|
+
let runEnd = runStart;
|
|
1371
|
+
while (runEnd + 1 < passingIndices.length && passingIndices[runEnd + 1] === passingIndices[runEnd] + 1) runEnd++;
|
|
1372
|
+
if (runEnd - runStart + 1 === 1) result.add(graph[passingIndices[runStart]].targetId);
|
|
1373
|
+
else {
|
|
1374
|
+
const peaks = [];
|
|
1375
|
+
for (let j = runStart; j <= runEnd; j++) {
|
|
1376
|
+
const idx = passingIndices[j];
|
|
1377
|
+
const score = normalizedScores[idx];
|
|
1378
|
+
const prevScore = j > runStart ? normalizedScores[passingIndices[j - 1]] : -Infinity;
|
|
1379
|
+
const nextScore = j < runEnd ? normalizedScores[passingIndices[j + 1]] : -Infinity;
|
|
1380
|
+
if (score > prevScore && score > nextScore) peaks.push(idx);
|
|
1381
|
+
}
|
|
1382
|
+
if (peaks.length > 0) for (const peakIdx of peaks) result.add(graph[peakIdx].targetId);
|
|
1383
|
+
else {
|
|
1384
|
+
let peakIdx = passingIndices[runStart];
|
|
1385
|
+
for (let j = runStart + 1; j <= runEnd; j++) {
|
|
1386
|
+
const idx = passingIndices[j];
|
|
1387
|
+
if (normalizedScores[idx] > normalizedScores[peakIdx]) peakIdx = idx;
|
|
1388
|
+
}
|
|
1389
|
+
result.add(graph[peakIdx].targetId);
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
runStart = runEnd + 1;
|
|
1393
|
+
}
|
|
1394
|
+
return result;
|
|
1036
1395
|
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Threshold-based pruning with NMS -- including normalization, O(N log N).
|
|
1398
|
+
*
|
|
1399
|
+
* 1. Scores are normalized to [0, 1] via percentile normalization.
|
|
1400
|
+
* 2. Edges with normalized score >= threshold are collected.
|
|
1401
|
+
* 3. Non-Maximum Suppression groups consecutive passing edges and keeps
|
|
1402
|
+
* only the peak per run, preventing near-duplicate frame selection
|
|
1403
|
+
* from a single visual transition.
|
|
1404
|
+
*
|
|
1405
|
+
* First and last frames are always preserved (boundary protection).
|
|
1406
|
+
*/
|
|
1037
1407
|
function pruneByThreshold(graph, frames, threshold) {
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
}
|
|
1049
|
-
const nmsTargets = suppressConsecutiveRuns(graph, passingIndices, normalized);
|
|
1050
|
-
for (const id of nmsTargets) {
|
|
1051
|
-
surviving.add(id);
|
|
1052
|
-
}
|
|
1053
|
-
return surviving;
|
|
1408
|
+
if (frames.length === 0) return /* @__PURE__ */ new Set();
|
|
1409
|
+
const surviving = /* @__PURE__ */ new Set();
|
|
1410
|
+
surviving.add(frames[0].id);
|
|
1411
|
+
surviving.add(frames[frames.length - 1].id);
|
|
1412
|
+
const normalized = normalizeScores(graph);
|
|
1413
|
+
const passingIndices = [];
|
|
1414
|
+
for (let i = 0; i < graph.length; i++) if (normalized[i] >= threshold) passingIndices.push(i);
|
|
1415
|
+
const nmsTargets = suppressConsecutiveRuns(graph, passingIndices, normalized);
|
|
1416
|
+
for (const id of nmsTargets) surviving.add(id);
|
|
1417
|
+
return surviving;
|
|
1054
1418
|
}
|
|
1419
|
+
/**
|
|
1420
|
+
* Combined threshold + count pruning -- 2-stage pipeline.
|
|
1421
|
+
*
|
|
1422
|
+
* Stage 1: pruneByThreshold -- keep all frames with normalized score >= threshold
|
|
1423
|
+
* Stage 2: if result exceeds maxCount, rebuild subgraph with synthetic edges
|
|
1424
|
+
* (min-score over each gap) and apply pruneTo on the surviving subset
|
|
1425
|
+
*
|
|
1426
|
+
* Edge reconstruction: for consecutive survivors A, B with removed frames
|
|
1427
|
+
* [x1, x2, ...] between them, the synthetic edge score is:
|
|
1428
|
+
* min(score(A->x1), score(x1->x2), ..., score(xN->B))
|
|
1429
|
+
* This preserves the "weakest link" semantics.
|
|
1430
|
+
*/
|
|
1055
1431
|
function pruneByThresholdWithCap(graph, frames, threshold, maxCount) {
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
}
|
|
1084
|
-
syntheticEdges.push({
|
|
1085
|
-
sourceId: srcSurvivor.id,
|
|
1086
|
-
targetId: tgtSurvivor.id,
|
|
1087
|
-
score: minScore === Infinity ? 0 : minScore
|
|
1088
|
-
});
|
|
1089
|
-
}
|
|
1090
|
-
return pruneTo(syntheticEdges, survivingFrames, maxCount);
|
|
1432
|
+
const thresholdSurvivors = pruneByThreshold(graph, frames, threshold);
|
|
1433
|
+
if (thresholdSurvivors.size <= maxCount) return thresholdSurvivors;
|
|
1434
|
+
const survivingFrames = filter(frames, (f) => thresholdSurvivors.has(f.id));
|
|
1435
|
+
const idToOrigIdx = /* @__PURE__ */ new Map();
|
|
1436
|
+
for (let i = 0; i < frames.length; i++) idToOrigIdx.set(frames[i].id, i);
|
|
1437
|
+
const edgeLookup = /* @__PURE__ */ new Map();
|
|
1438
|
+
for (const e of graph) edgeLookup.set(`${e.sourceId}:${e.targetId}`, e.score);
|
|
1439
|
+
const syntheticEdges = [];
|
|
1440
|
+
for (let i = 0; i < survivingFrames.length - 1; i++) {
|
|
1441
|
+
const srcSurvivor = survivingFrames[i];
|
|
1442
|
+
const tgtSurvivor = survivingFrames[i + 1];
|
|
1443
|
+
const srcOrigIdx = idToOrigIdx.get(srcSurvivor.id);
|
|
1444
|
+
const tgtOrigIdx = idToOrigIdx.get(tgtSurvivor.id);
|
|
1445
|
+
let minScore = Infinity;
|
|
1446
|
+
for (let j = srcOrigIdx; j < tgtOrigIdx; j++) {
|
|
1447
|
+
const fromId = frames[j].id;
|
|
1448
|
+
const toId = frames[j + 1].id;
|
|
1449
|
+
const score = edgeLookup.get(`${fromId}:${toId}`) ?? 0;
|
|
1450
|
+
if (score < minScore) minScore = score;
|
|
1451
|
+
}
|
|
1452
|
+
syntheticEdges.push({
|
|
1453
|
+
sourceId: srcSurvivor.id,
|
|
1454
|
+
targetId: tgtSurvivor.id,
|
|
1455
|
+
score: minScore === Infinity ? 0 : minScore
|
|
1456
|
+
});
|
|
1457
|
+
}
|
|
1458
|
+
return pruneTo(syntheticEdges, survivingFrames, maxCount);
|
|
1091
1459
|
}
|
|
1460
|
+
var init_pruner$1 = __esmMin((() => {
|
|
1461
|
+
init_normalize_scores();
|
|
1462
|
+
init_min_heap();
|
|
1463
|
+
}));
|
|
1092
1464
|
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1465
|
+
//#endregion
|
|
1466
|
+
//#region src/core/pruner/index.ts
|
|
1467
|
+
var init_pruner = __esmMin((() => {
|
|
1468
|
+
init_pruner$1();
|
|
1469
|
+
}));
|
|
1097
1470
|
|
|
1098
|
-
|
|
1471
|
+
//#endregion
|
|
1472
|
+
//#region src/core/segmenter/scheduling/concurrency.ts
|
|
1473
|
+
/**
|
|
1474
|
+
* Creates a concurrency limiter that runs at most `limit` tasks in parallel.
|
|
1475
|
+
* Lightweight replacement for p-limit to avoid external dependency.
|
|
1476
|
+
*/
|
|
1099
1477
|
function concurrencyLimit(limit) {
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
}
|
|
1114
|
-
};
|
|
1478
|
+
limit = Math.max(1, limit);
|
|
1479
|
+
let active = 0;
|
|
1480
|
+
const queue = [];
|
|
1481
|
+
return async (fn) => {
|
|
1482
|
+
while (active >= limit) await new Promise((resolve) => queue.push(resolve));
|
|
1483
|
+
active++;
|
|
1484
|
+
try {
|
|
1485
|
+
return await fn();
|
|
1486
|
+
} finally {
|
|
1487
|
+
active--;
|
|
1488
|
+
queue.shift()?.();
|
|
1489
|
+
}
|
|
1490
|
+
};
|
|
1115
1491
|
}
|
|
1492
|
+
var init_concurrency = __esmMin((() => {}));
|
|
1116
1493
|
|
|
1117
|
-
|
|
1494
|
+
//#endregion
|
|
1495
|
+
//#region src/core/segmenter/segmenter.ts
|
|
1496
|
+
/**
|
|
1497
|
+
* Determine whether segmentation should be used.
|
|
1498
|
+
* Returns false for frames mode and GIF files.
|
|
1499
|
+
* Actual duration check happens inside runSegmentedPipeline after metadata fetch.
|
|
1500
|
+
*/
|
|
1118
1501
|
function shouldSegment(resolvedOptions, originalOptions) {
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1502
|
+
if (resolvedOptions.mode === "frames") return false;
|
|
1503
|
+
if (originalOptions.mode === "file") {
|
|
1504
|
+
if (originalOptions.inputPath.toLowerCase().endsWith(".gif")) return false;
|
|
1505
|
+
}
|
|
1506
|
+
return true;
|
|
1124
1507
|
}
|
|
1508
|
+
/**
|
|
1509
|
+
* Partition the global extraction grid into nonempty logical segments.
|
|
1510
|
+
* @param totalDuration Positive source duration in seconds.
|
|
1511
|
+
* @param maxSegmentDuration Positive logical segment width in seconds.
|
|
1512
|
+
* @param maxFrames Candidate budget, defensively raised to at least two.
|
|
1513
|
+
* @param fps Positive requested sampling frequency.
|
|
1514
|
+
* @returns Contiguous plan indices with grid-aligned seeks and overlap-inclusive limits.
|
|
1515
|
+
*/
|
|
1125
1516
|
function computeSegmentPlan(totalDuration, maxSegmentDuration, maxFrames, fps) {
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
});
|
|
1176
|
-
}
|
|
1177
|
-
const totalAllocated = segments.reduce(
|
|
1178
|
-
(sum, s) => sum + s.allocatedFrames,
|
|
1179
|
-
0
|
|
1180
|
-
);
|
|
1181
|
-
if (totalAllocated > maxFrames) {
|
|
1182
|
-
segments[segments.length - 1].allocatedFrames -= totalAllocated - maxFrames;
|
|
1183
|
-
}
|
|
1184
|
-
return segments;
|
|
1517
|
+
const frameLimit = Math.max(2, maxFrames);
|
|
1518
|
+
const effectiveFps = Math.min(fps, frameLimit / totalDuration);
|
|
1519
|
+
if (totalDuration <= maxSegmentDuration) return [{
|
|
1520
|
+
index: 0,
|
|
1521
|
+
startTime: 0,
|
|
1522
|
+
endTime: totalDuration,
|
|
1523
|
+
duration: totalDuration,
|
|
1524
|
+
allocatedFrames: frameLimit,
|
|
1525
|
+
effectiveFps,
|
|
1526
|
+
overlapBefore: 0,
|
|
1527
|
+
overlapAfter: 0,
|
|
1528
|
+
extractStartTime: 0,
|
|
1529
|
+
extractDuration: totalDuration
|
|
1530
|
+
}];
|
|
1531
|
+
const segments = [];
|
|
1532
|
+
for (let slot = 0; slot < frameLimit; slot++) {
|
|
1533
|
+
const timestamp = slot / effectiveFps;
|
|
1534
|
+
if (timestamp >= totalDuration) break;
|
|
1535
|
+
const startTime = Math.floor(timestamp / maxSegmentDuration) * maxSegmentDuration;
|
|
1536
|
+
const previous = segments[segments.length - 1];
|
|
1537
|
+
if (previous?.startTime === startTime) {
|
|
1538
|
+
previous.allocatedFrames++;
|
|
1539
|
+
continue;
|
|
1540
|
+
}
|
|
1541
|
+
const endTime = Math.min(startTime + maxSegmentDuration, totalDuration);
|
|
1542
|
+
segments.push({
|
|
1543
|
+
index: segments.length,
|
|
1544
|
+
startTime,
|
|
1545
|
+
endTime,
|
|
1546
|
+
duration: endTime - startTime,
|
|
1547
|
+
allocatedFrames: 1,
|
|
1548
|
+
effectiveFps,
|
|
1549
|
+
overlapBefore: 0,
|
|
1550
|
+
overlapAfter: 0,
|
|
1551
|
+
extractStartTime: timestamp,
|
|
1552
|
+
extractDuration: 0
|
|
1553
|
+
});
|
|
1554
|
+
}
|
|
1555
|
+
let firstSlot = 0;
|
|
1556
|
+
for (const segment of segments) {
|
|
1557
|
+
const nextSlot = firstSlot + segment.allocatedFrames;
|
|
1558
|
+
segment.overlapBefore = segment.index > 0 ? 1 : 0;
|
|
1559
|
+
segment.overlapAfter = segment.index < segments.length - 1 ? 1 : 0;
|
|
1560
|
+
segment.extractStartTime = (firstSlot - segment.overlapBefore) / effectiveFps;
|
|
1561
|
+
segment.extractDuration = (segment.overlapAfter ? Math.min(totalDuration, (nextSlot + 1) / effectiveFps) : totalDuration) - segment.extractStartTime;
|
|
1562
|
+
segment.allocatedFrames += segment.overlapBefore + segment.overlapAfter;
|
|
1563
|
+
firstSlot = nextSlot;
|
|
1564
|
+
}
|
|
1565
|
+
return segments;
|
|
1185
1566
|
}
|
|
1567
|
+
/**
|
|
1568
|
+
* Collect all frames from every segment, adjusting timestamps by extractStartTime.
|
|
1569
|
+
*/
|
|
1186
1570
|
function collectAllFrames(segmentResults) {
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
localId: frame.id
|
|
1198
|
-
});
|
|
1199
|
-
}
|
|
1200
|
-
}
|
|
1201
|
-
return allFrames;
|
|
1571
|
+
const allFrames = [];
|
|
1572
|
+
for (const result of segmentResults) for (const frame of result.frames) allFrames.push({
|
|
1573
|
+
frame: {
|
|
1574
|
+
...frame,
|
|
1575
|
+
timestamp: frame.timestamp + result.segment.extractStartTime
|
|
1576
|
+
},
|
|
1577
|
+
segmentIndex: result.segment.index,
|
|
1578
|
+
localId: frame.id
|
|
1579
|
+
});
|
|
1580
|
+
return allFrames;
|
|
1202
1581
|
}
|
|
1582
|
+
/**
|
|
1583
|
+
* Sort frames in place and alias overlap duplicates to the first survivor.
|
|
1584
|
+
* @param frames Collected entries whose segment index and local ID identify a frame.
|
|
1585
|
+
* @param effectiveFps Positive sampling frequency; half a frame interval is the threshold.
|
|
1586
|
+
* @returns Timestamp-ordered survivors and duplicate keys pointing directly to survivor keys.
|
|
1587
|
+
*/
|
|
1203
1588
|
function deduplicateFrames(frames, effectiveFps) {
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1589
|
+
frames.sort((a, b) => a.frame.timestamp - b.frame.timestamp);
|
|
1590
|
+
const dupThreshold = 1 / (effectiveFps * 2);
|
|
1591
|
+
const unique = [];
|
|
1592
|
+
const aliases = /* @__PURE__ */ new Map();
|
|
1593
|
+
for (const entry of frames) {
|
|
1594
|
+
if (unique.length > 0) {
|
|
1595
|
+
const last = unique[unique.length - 1];
|
|
1596
|
+
if (Math.abs(entry.frame.timestamp - last.frame.timestamp) < dupThreshold) {
|
|
1597
|
+
aliases.set(`${entry.segmentIndex}:${entry.localId}`, `${last.segmentIndex}:${last.localId}`);
|
|
1598
|
+
continue;
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
unique.push(entry);
|
|
1602
|
+
}
|
|
1603
|
+
return {
|
|
1604
|
+
unique,
|
|
1605
|
+
aliases
|
|
1606
|
+
};
|
|
1217
1607
|
}
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1608
|
+
/**
|
|
1609
|
+
* Assign sequential global IDs and retain duplicate local IDs as aliases.
|
|
1610
|
+
* @param uniqueFrames Timestamp-ordered survivors with distinct segment/local keys.
|
|
1611
|
+
* @param aliases Duplicate keys pointing directly to keys in uniqueFrames.
|
|
1612
|
+
* @returns Remapped frames and a global ID lookup covering survivors and duplicates.
|
|
1613
|
+
*/
|
|
1614
|
+
function remapFrameIds(uniqueFrames, aliases) {
|
|
1615
|
+
const globalIdMap = /* @__PURE__ */ new Map();
|
|
1616
|
+
const frames = uniqueFrames.map((entry, globalId) => {
|
|
1617
|
+
globalIdMap.set(`${entry.segmentIndex}:${entry.localId}`, globalId);
|
|
1618
|
+
return {
|
|
1619
|
+
id: globalId,
|
|
1620
|
+
timestamp: entry.frame.timestamp,
|
|
1621
|
+
extractPath: entry.frame.extractPath
|
|
1622
|
+
};
|
|
1623
|
+
});
|
|
1624
|
+
for (const [alias, survivor] of aliases) globalIdMap.set(alias, globalIdMap.get(survivor));
|
|
1625
|
+
return {
|
|
1626
|
+
frames,
|
|
1627
|
+
globalIdMap
|
|
1628
|
+
};
|
|
1229
1629
|
}
|
|
1630
|
+
/**
|
|
1631
|
+
* Remap edges, dropping missing endpoints and self loops while keeping the highest pair score.
|
|
1632
|
+
* @param segmentResults Segment-local edges in encounter order.
|
|
1633
|
+
* @param globalIdMap Survivor and duplicate local keys mapped to global IDs.
|
|
1634
|
+
* @returns One edge per surviving directed pair without changing its score.
|
|
1635
|
+
*/
|
|
1230
1636
|
function remapEdges(segmentResults, globalIdMap) {
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
targetId: newTargetId,
|
|
1257
|
-
score: edge.score
|
|
1258
|
-
});
|
|
1259
|
-
}
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
return edges;
|
|
1637
|
+
const edges = [];
|
|
1638
|
+
const edgeMap = /* @__PURE__ */ new Map();
|
|
1639
|
+
for (const result of segmentResults) for (const edge of result.edges) {
|
|
1640
|
+
const newSourceId = globalIdMap.get(`${result.segment.index}:${edge.sourceId}`);
|
|
1641
|
+
const newTargetId = globalIdMap.get(`${result.segment.index}:${edge.targetId}`);
|
|
1642
|
+
if (newSourceId === void 0 || newTargetId === void 0) continue;
|
|
1643
|
+
if (newSourceId === newTargetId) continue;
|
|
1644
|
+
const edgeKey = `${newSourceId}-${newTargetId}`;
|
|
1645
|
+
const existingIdx = edgeMap.get(edgeKey);
|
|
1646
|
+
if (existingIdx !== void 0) {
|
|
1647
|
+
if (edges[existingIdx].score < edge.score) edges[existingIdx] = {
|
|
1648
|
+
sourceId: newSourceId,
|
|
1649
|
+
targetId: newTargetId,
|
|
1650
|
+
score: edge.score
|
|
1651
|
+
};
|
|
1652
|
+
} else {
|
|
1653
|
+
edgeMap.set(edgeKey, edges.length);
|
|
1654
|
+
edges.push({
|
|
1655
|
+
sourceId: newSourceId,
|
|
1656
|
+
targetId: newTargetId,
|
|
1657
|
+
score: edge.score
|
|
1658
|
+
});
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
return edges;
|
|
1263
1662
|
}
|
|
1663
|
+
/**
|
|
1664
|
+
* Remap animations, dropping missing or collapsed endpoints and retaining the first pair entry.
|
|
1665
|
+
* @param segmentResults Segment-local tracker entries in encounter order.
|
|
1666
|
+
* @param globalIdMap Survivor and duplicate local keys mapped to global IDs.
|
|
1667
|
+
* @returns One animation per directed pair with its original tracker duration and metadata.
|
|
1668
|
+
*/
|
|
1264
1669
|
function remapAnimations(segmentResults, globalIdMap) {
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
}
|
|
1281
|
-
}
|
|
1282
|
-
return animations;
|
|
1670
|
+
const animations = /* @__PURE__ */ new Map();
|
|
1671
|
+
for (const result of segmentResults) for (const anim of result.animations) {
|
|
1672
|
+
const newStartId = globalIdMap.get(`${result.segment.index}:${anim.startFrameId}`);
|
|
1673
|
+
const newEndId = globalIdMap.get(`${result.segment.index}:${anim.endFrameId}`);
|
|
1674
|
+
if (newStartId === void 0 || newEndId === void 0) continue;
|
|
1675
|
+
if (newStartId === newEndId) continue;
|
|
1676
|
+
const animationKey = `${newStartId}-${newEndId}`;
|
|
1677
|
+
if (animations.has(animationKey)) continue;
|
|
1678
|
+
animations.set(animationKey, {
|
|
1679
|
+
...anim,
|
|
1680
|
+
startFrameId: newStartId,
|
|
1681
|
+
endFrameId: newEndId
|
|
1682
|
+
});
|
|
1683
|
+
}
|
|
1684
|
+
return [...animations.values()];
|
|
1283
1685
|
}
|
|
1686
|
+
/**
|
|
1687
|
+
* Merge multiple segment results into a single unified frame/edge/animation set.
|
|
1688
|
+
* @param segmentResults Local frames, edges and tracker entries with distinct segment indices.
|
|
1689
|
+
* @returns Global timestamp-ordered frames, aliased edges and animations without self loops.
|
|
1690
|
+
* Duplicate edges keep the higher score; duplicate animations keep the first tracker entry.
|
|
1691
|
+
*/
|
|
1284
1692
|
function mergeSegmentFrames(segmentResults) {
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1693
|
+
if (segmentResults.length === 0) return {
|
|
1694
|
+
frames: [],
|
|
1695
|
+
edges: [],
|
|
1696
|
+
animations: [],
|
|
1697
|
+
analysisResolution: {
|
|
1698
|
+
width: 0,
|
|
1699
|
+
height: 0
|
|
1700
|
+
}
|
|
1701
|
+
};
|
|
1702
|
+
const effectiveFps = segmentResults[0].segment.effectiveFps;
|
|
1703
|
+
const { unique, aliases } = deduplicateFrames(collectAllFrames(segmentResults), effectiveFps);
|
|
1704
|
+
const { frames, globalIdMap } = remapFrameIds(unique, aliases);
|
|
1705
|
+
return {
|
|
1706
|
+
frames,
|
|
1707
|
+
edges: remapEdges(segmentResults, globalIdMap),
|
|
1708
|
+
animations: remapAnimations(segmentResults, globalIdMap),
|
|
1709
|
+
analysisResolution: segmentResults[0].analysisResolution
|
|
1710
|
+
};
|
|
1295
1711
|
}
|
|
1296
1712
|
function buildSegmentContext(segment, frames, segmentWorkspacePath, resolvedOptions, onProgress) {
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1713
|
+
return {
|
|
1714
|
+
options: {
|
|
1715
|
+
...resolvedOptions,
|
|
1716
|
+
fps: segment.effectiveFps,
|
|
1717
|
+
maxFrames: segment.allocatedFrames
|
|
1718
|
+
},
|
|
1719
|
+
workspacePath: segmentWorkspacePath,
|
|
1720
|
+
effectiveFps: segment.effectiveFps,
|
|
1721
|
+
frames,
|
|
1722
|
+
graph: [],
|
|
1723
|
+
status: "ANALYZING",
|
|
1724
|
+
emitProgress: onProgress
|
|
1725
|
+
};
|
|
1309
1726
|
}
|
|
1727
|
+
/**
|
|
1728
|
+
* Extract frames for a single segment and analyze them.
|
|
1729
|
+
* Each segment uses an isolated workspace directory.
|
|
1730
|
+
*/
|
|
1310
1731
|
async function processSegment(inputPath, segment, workspacePath, resolvedOptions, onProgress) {
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
const { edges, animations } = await analyzeFrames(ctx);
|
|
1331
|
-
return { segment, frames, edges, animations };
|
|
1732
|
+
const frames = await extractFramesForRange(inputPath, join(workspacePath, "frames"), segment.effectiveFps, resolvedOptions.scale, segment.extractStartTime, segment.extractDuration, segment.allocatedFrames);
|
|
1733
|
+
if (frames.length < 2) return {
|
|
1734
|
+
segment,
|
|
1735
|
+
frames,
|
|
1736
|
+
edges: [],
|
|
1737
|
+
animations: [],
|
|
1738
|
+
analysisResolution: {
|
|
1739
|
+
width: 0,
|
|
1740
|
+
height: 0
|
|
1741
|
+
}
|
|
1742
|
+
};
|
|
1743
|
+
const { edges, animations, analysisResolution } = await analyzeFrames(buildSegmentContext(segment, frames, workspacePath, resolvedOptions, onProgress));
|
|
1744
|
+
return {
|
|
1745
|
+
segment,
|
|
1746
|
+
frames,
|
|
1747
|
+
edges,
|
|
1748
|
+
animations,
|
|
1749
|
+
analysisResolution
|
|
1750
|
+
};
|
|
1332
1751
|
}
|
|
1752
|
+
/**
|
|
1753
|
+
* Full segmented pipeline: metadata → plan → parallel extract+analyze → merge → prune → finalize.
|
|
1754
|
+
* Called from runPipeline when shouldSegment() returns true.
|
|
1755
|
+
*/
|
|
1333
1756
|
async function runSegmentedPipeline(options, resolvedOptions) {
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
workspacePath: mainWorkspace,
|
|
1410
|
-
frames,
|
|
1411
|
-
graph: edges,
|
|
1412
|
-
animations,
|
|
1413
|
-
status: "FINALIZING",
|
|
1414
|
-
emitProgress: (percent) => options.onProgress?.("FINALIZING", percent)
|
|
1415
|
-
};
|
|
1416
|
-
let outputFiles = [];
|
|
1417
|
-
let outputBuffers;
|
|
1418
|
-
if (resolvedOptions.mode === "buffer" || resolvedOptions.mode === "frames") {
|
|
1419
|
-
outputBuffers = await readFramesAsBuffers(
|
|
1420
|
-
prunedFrames,
|
|
1421
|
-
resolvedOptions.quality
|
|
1422
|
-
);
|
|
1423
|
-
} else {
|
|
1424
|
-
outputFiles = await finalizeOutput(ctx, prunedFrames);
|
|
1425
|
-
}
|
|
1426
|
-
options.onProgress?.("FINALIZING", 100);
|
|
1427
|
-
logger.success(
|
|
1428
|
-
`Segmented pipeline: ${prunedFrames.length} scenes from ${frames.length} frames (${segments.length} segments)`
|
|
1429
|
-
);
|
|
1430
|
-
return {
|
|
1431
|
-
success: true,
|
|
1432
|
-
originalFramesCount: frames.length,
|
|
1433
|
-
prunedFramesCount: prunedFrames.length,
|
|
1434
|
-
outputFiles,
|
|
1435
|
-
outputBuffers,
|
|
1436
|
-
animations,
|
|
1437
|
-
video: {
|
|
1438
|
-
originalDurationMs: totalDuration * 1e3,
|
|
1439
|
-
fps: resolvedOptions.fps,
|
|
1440
|
-
resolution: {
|
|
1441
|
-
width: resolvedOptions.scale,
|
|
1442
|
-
height: Math.round(resolvedOptions.scale * 9 / 16)
|
|
1443
|
-
}
|
|
1444
|
-
},
|
|
1445
|
-
executionTimeMs: Date.now() - pipelineStart
|
|
1446
|
-
};
|
|
1447
|
-
} catch (error) {
|
|
1448
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
1449
|
-
logger.error(`Segmented pipeline failed: ${err.message}`);
|
|
1450
|
-
throw err;
|
|
1451
|
-
} finally {
|
|
1452
|
-
if (!resolvedOptions.debug) {
|
|
1453
|
-
await cleanupWorkspace(mainWorkspace);
|
|
1454
|
-
} else {
|
|
1455
|
-
logger.debug(`Debug mode: workspace preserved at ${mainWorkspace}`);
|
|
1456
|
-
}
|
|
1457
|
-
}
|
|
1757
|
+
const pipelineStart = Date.now();
|
|
1758
|
+
const sessionId = randomUUID();
|
|
1759
|
+
let mainWorkspace = "";
|
|
1760
|
+
try {
|
|
1761
|
+
mainWorkspace = await createWorkspace(sessionId);
|
|
1762
|
+
logger.debug(`Segmented pipeline: workspace at ${mainWorkspace}`);
|
|
1763
|
+
const { resolvedInputPath } = await resolveInput(options, mainWorkspace);
|
|
1764
|
+
const inputPath = resolvedInputPath ?? resolvedOptions.inputPath;
|
|
1765
|
+
if (!inputPath) throw new Error("No input path available for segmented pipeline");
|
|
1766
|
+
const metadata = await getVideoMetadata(inputPath);
|
|
1767
|
+
const totalDuration = parseFloat(metadata.format?.duration ?? "0");
|
|
1768
|
+
if (totalDuration <= 0) throw new Error(`Invalid video duration: ${totalDuration}`);
|
|
1769
|
+
logger.debug(`Video duration: ${totalDuration}s`);
|
|
1770
|
+
const segments = computeSegmentPlan(totalDuration, resolvedOptions.maxSegmentDuration, resolvedOptions.maxFrames, resolvedOptions.fps);
|
|
1771
|
+
logger.debug(`Segment plan: ${segments.length} segments`);
|
|
1772
|
+
const limit = concurrencyLimit(resolvedOptions.concurrency);
|
|
1773
|
+
const segmentProgresses = new Array(segments.length).fill(0);
|
|
1774
|
+
const weights = map(segments, (s) => s.duration / totalDuration);
|
|
1775
|
+
const emitOverallProgress = (phase) => {
|
|
1776
|
+
if (!options.onProgress) return;
|
|
1777
|
+
const overall = weights.reduce((sum, w, i) => sum + w * (segmentProgresses[i] ?? 0), 0);
|
|
1778
|
+
options.onProgress(phase, Math.min(100, overall));
|
|
1779
|
+
};
|
|
1780
|
+
options.onProgress?.("EXTRACTING", 0);
|
|
1781
|
+
const results = await Promise.all(map(segments, (segment) => limit(async () => {
|
|
1782
|
+
const segWorkspace = await createSegmentWorkspace(mainWorkspace, segment.index);
|
|
1783
|
+
return await processSegment(inputPath, segment, segWorkspace, resolvedOptions, (percent) => {
|
|
1784
|
+
segmentProgresses[segment.index] = percent;
|
|
1785
|
+
emitOverallProgress("ANALYZING");
|
|
1786
|
+
});
|
|
1787
|
+
})));
|
|
1788
|
+
options.onProgress?.("ANALYZING", 100);
|
|
1789
|
+
const { frames, edges, animations, analysisResolution } = mergeSegmentFrames(results);
|
|
1790
|
+
logger.debug(`Merged: ${frames.length} frames, ${edges.length} edges, ${animations.length} animations`);
|
|
1791
|
+
options.onProgress?.("PRUNING", 0);
|
|
1792
|
+
const survivingIds = pruneByThresholdWithCap(edges, frames, resolvedOptions.threshold, resolvedOptions.count);
|
|
1793
|
+
const prunedFrames = filter(frames, (f) => survivingIds.has(f.id));
|
|
1794
|
+
options.onProgress?.("PRUNING", 100);
|
|
1795
|
+
options.onProgress?.("FINALIZING", 0);
|
|
1796
|
+
const ctx = {
|
|
1797
|
+
options: resolvedOptions,
|
|
1798
|
+
effectiveFps: segments[0]?.effectiveFps,
|
|
1799
|
+
sourceDurationSec: totalDuration,
|
|
1800
|
+
analysisResolution,
|
|
1801
|
+
workspacePath: mainWorkspace,
|
|
1802
|
+
frames,
|
|
1803
|
+
graph: edges,
|
|
1804
|
+
animations,
|
|
1805
|
+
status: "FINALIZING",
|
|
1806
|
+
emitProgress: (percent) => options.onProgress?.("FINALIZING", percent)
|
|
1807
|
+
};
|
|
1808
|
+
let outputFiles = [];
|
|
1809
|
+
let outputBuffers;
|
|
1810
|
+
if (resolvedOptions.mode === "buffer" || resolvedOptions.mode === "frames") outputBuffers = await readFramesAsBuffers(prunedFrames, resolvedOptions.quality);
|
|
1811
|
+
else outputFiles = await finalizeOutput(ctx, prunedFrames);
|
|
1812
|
+
options.onProgress?.("FINALIZING", 100);
|
|
1813
|
+
logger.success(`Segmented pipeline: ${prunedFrames.length} scenes from ${frames.length} frames (${segments.length} segments)`);
|
|
1814
|
+
const outputMetadata = await buildVideoMetadata(ctx, prunedFrames, analysisResolution);
|
|
1815
|
+
return {
|
|
1816
|
+
success: true,
|
|
1817
|
+
originalFramesCount: frames.length,
|
|
1818
|
+
prunedFramesCount: prunedFrames.length,
|
|
1819
|
+
outputFiles,
|
|
1820
|
+
outputBuffers,
|
|
1821
|
+
...outputMetadata,
|
|
1822
|
+
executionTimeMs: Date.now() - pipelineStart
|
|
1823
|
+
};
|
|
1824
|
+
} catch (error) {
|
|
1825
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1826
|
+
logger.error(`Segmented pipeline failed: ${err.message}`);
|
|
1827
|
+
throw err;
|
|
1828
|
+
} finally {
|
|
1829
|
+
if (!resolvedOptions.debug) await cleanupWorkspace(mainWorkspace);
|
|
1830
|
+
else logger.debug(`Debug mode: workspace preserved at ${mainWorkspace}`);
|
|
1831
|
+
}
|
|
1458
1832
|
}
|
|
1833
|
+
var init_segmenter$1 = __esmMin((() => {
|
|
1834
|
+
init_concurrency();
|
|
1835
|
+
init_logger();
|
|
1836
|
+
init_analyzer();
|
|
1837
|
+
init_build_video_metadata();
|
|
1838
|
+
init_extractor();
|
|
1839
|
+
init_input_resolver();
|
|
1840
|
+
init_pruner();
|
|
1841
|
+
init_workspace();
|
|
1842
|
+
}));
|
|
1459
1843
|
|
|
1460
|
-
|
|
1844
|
+
//#endregion
|
|
1845
|
+
//#region src/core/segmenter/index.ts
|
|
1846
|
+
var init_segmenter = __esmMin((() => {
|
|
1847
|
+
init_segmenter$1();
|
|
1848
|
+
}));
|
|
1849
|
+
|
|
1850
|
+
//#endregion
|
|
1851
|
+
//#region src/core/orchestrator/orchestrator.ts
|
|
1461
1852
|
async function runPipeline(options) {
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
outputBuffers,
|
|
1539
|
-
animations: ctx.animations,
|
|
1540
|
-
video: {
|
|
1541
|
-
originalDurationMs: ctx.frames.length / ctx.options.fps * 1e3,
|
|
1542
|
-
fps: ctx.options.fps,
|
|
1543
|
-
resolution: {
|
|
1544
|
-
width: ctx.options.scale,
|
|
1545
|
-
height: Math.round(ctx.options.scale * 9 / 16)
|
|
1546
|
-
}
|
|
1547
|
-
},
|
|
1548
|
-
executionTimeMs: Date.now() - startTime
|
|
1549
|
-
};
|
|
1550
|
-
} catch (error) {
|
|
1551
|
-
ctx.status = "FAILED";
|
|
1552
|
-
ctx.error = error instanceof Error ? error : new Error(String(error));
|
|
1553
|
-
logger.error(`Pipeline failed: ${ctx.error.message}`);
|
|
1554
|
-
throw ctx.error;
|
|
1555
|
-
} finally {
|
|
1556
|
-
if (!resolvedOptions.debug) {
|
|
1557
|
-
await cleanupWorkspace(ctx.workspacePath);
|
|
1558
|
-
} else {
|
|
1559
|
-
logger.debug(`Debug mode: workspace preserved at ${ctx.workspacePath}`);
|
|
1560
|
-
}
|
|
1561
|
-
}
|
|
1853
|
+
setDebugMode(options.debug ?? false);
|
|
1854
|
+
const resolvedOptions = resolveOptions(options);
|
|
1855
|
+
if (shouldSegment(resolvedOptions, options)) return runSegmentedPipeline(options, resolvedOptions);
|
|
1856
|
+
const startTime = Date.now();
|
|
1857
|
+
const sessionId = randomUUID();
|
|
1858
|
+
const ctx = {
|
|
1859
|
+
options: resolvedOptions,
|
|
1860
|
+
workspacePath: "",
|
|
1861
|
+
frames: [],
|
|
1862
|
+
graph: [],
|
|
1863
|
+
status: "INIT",
|
|
1864
|
+
emitProgress: (percent) => {
|
|
1865
|
+
if (options.onProgress && ctx.status !== "INIT" && ctx.status !== "SUCCESS" && ctx.status !== "FAILED") options.onProgress(ctx.status, percent);
|
|
1866
|
+
}
|
|
1867
|
+
};
|
|
1868
|
+
try {
|
|
1869
|
+
ctx.workspacePath = await createWorkspace(sessionId);
|
|
1870
|
+
logger.debug(`Workspace created: ${ctx.workspacePath}`);
|
|
1871
|
+
ctx.status = "EXTRACTING";
|
|
1872
|
+
const { frames: resolvedFrames, resolvedInputPath } = await resolveInput(options, ctx.workspacePath);
|
|
1873
|
+
if (resolvedOptions.mode === "frames") {
|
|
1874
|
+
ctx.frames = resolvedFrames;
|
|
1875
|
+
ctx.effectiveFps = 1;
|
|
1876
|
+
} else {
|
|
1877
|
+
const extractCtx = {
|
|
1878
|
+
...ctx,
|
|
1879
|
+
options: {
|
|
1880
|
+
...resolvedOptions,
|
|
1881
|
+
inputPath: resolvedInputPath
|
|
1882
|
+
}
|
|
1883
|
+
};
|
|
1884
|
+
ctx.frames = await extractFrames(extractCtx);
|
|
1885
|
+
ctx.effectiveFps = extractCtx.effectiveFps;
|
|
1886
|
+
ctx.sourceDurationSec = extractCtx.sourceDurationSec;
|
|
1887
|
+
}
|
|
1888
|
+
ctx.emitProgress(100);
|
|
1889
|
+
ctx.status = "ANALYZING";
|
|
1890
|
+
const { edges, animations, analysisResolution } = await analyzeFrames(ctx);
|
|
1891
|
+
ctx.graph = edges;
|
|
1892
|
+
ctx.animations = animations;
|
|
1893
|
+
ctx.analysisResolution = analysisResolution;
|
|
1894
|
+
ctx.status = "PRUNING";
|
|
1895
|
+
const survivingIds = pruneByThresholdWithCap(ctx.graph, ctx.frames, resolvedOptions.threshold, resolvedOptions.count);
|
|
1896
|
+
const prunedFrames = filter(ctx.frames, (f) => survivingIds.has(f.id));
|
|
1897
|
+
ctx.emitProgress(100);
|
|
1898
|
+
ctx.status = "FINALIZING";
|
|
1899
|
+
let outputFiles = [];
|
|
1900
|
+
let outputBuffers;
|
|
1901
|
+
if (resolvedOptions.mode === "buffer" || resolvedOptions.mode === "frames") {
|
|
1902
|
+
outputBuffers = await readFramesAsBuffers(prunedFrames, resolvedOptions.quality);
|
|
1903
|
+
ctx.emitProgress(100);
|
|
1904
|
+
} else {
|
|
1905
|
+
outputFiles = await finalizeOutput(ctx, prunedFrames);
|
|
1906
|
+
ctx.emitProgress(100);
|
|
1907
|
+
}
|
|
1908
|
+
ctx.status = "SUCCESS";
|
|
1909
|
+
logger.success(`Extracted ${prunedFrames.length} scenes from ${ctx.frames.length} frames`);
|
|
1910
|
+
const metadata = await buildVideoMetadata(ctx, prunedFrames, analysisResolution);
|
|
1911
|
+
return {
|
|
1912
|
+
success: true,
|
|
1913
|
+
originalFramesCount: ctx.frames.length,
|
|
1914
|
+
prunedFramesCount: prunedFrames.length,
|
|
1915
|
+
outputFiles,
|
|
1916
|
+
outputBuffers,
|
|
1917
|
+
...metadata,
|
|
1918
|
+
executionTimeMs: Date.now() - startTime
|
|
1919
|
+
};
|
|
1920
|
+
} catch (error) {
|
|
1921
|
+
ctx.status = "FAILED";
|
|
1922
|
+
ctx.error = error instanceof Error ? error : new Error(String(error));
|
|
1923
|
+
logger.error(`Pipeline failed: ${ctx.error.message}`);
|
|
1924
|
+
throw ctx.error;
|
|
1925
|
+
} finally {
|
|
1926
|
+
if (!resolvedOptions.debug) await cleanupWorkspace(ctx.workspacePath);
|
|
1927
|
+
else logger.debug(`Debug mode: workspace preserved at ${ctx.workspacePath}`);
|
|
1928
|
+
}
|
|
1562
1929
|
}
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1930
|
+
var init_orchestrator = __esmMin((() => {
|
|
1931
|
+
init_logger();
|
|
1932
|
+
init_analyzer();
|
|
1933
|
+
init_build_video_metadata();
|
|
1934
|
+
init_extractor();
|
|
1935
|
+
init_input_resolver();
|
|
1936
|
+
init_pruner();
|
|
1937
|
+
init_segmenter();
|
|
1938
|
+
init_workspace();
|
|
1939
|
+
}));
|
|
1940
|
+
|
|
1941
|
+
//#endregion
|
|
1942
|
+
//#region src/index.ts
|
|
1943
|
+
init_orchestrator();
|
|
1944
|
+
|
|
1945
|
+
//#endregion
|
|
1946
|
+
export { runPipeline as extractScenes };
|