editorbrain 0.43.0 → 0.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,255 @@
1
+ #!/usr/bin/env node
2
+ // Optional external-tool adapter. No downloads, product credits, or loudness processing.
3
+ import { spawn } from 'node:child_process';
4
+ import { createHash } from 'node:crypto';
5
+ import { createReadStream } from 'node:fs';
6
+ import { access, lstat, mkdir, open, realpath, rm, statfs, writeFile } from 'node:fs/promises';
7
+ import { constants } from 'node:fs';
8
+ import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ export const MODEL_SHA256 = 'c94d91f70911001c946e0fabb4aa9adc37045f45a03b56008cb0c8244cb63616';
12
+ const SAMPLE_RATE = 48000;
13
+ const MAX_SECONDS = 3600;
14
+ const MAX_LOG_BYTES = 1024 * 1024;
15
+ const HELP = `Optional DeepFilterNet3 voice cleanup (Node.js 24+, ffmpeg and ffprobe).
16
+
17
+ node deepfilter-cleanup.mjs --input <local audio/video> --out <NEW directory>
18
+ --binary <official deep-filter v0.5.6> --model <DeepFilterNet3_onnx.tar.gz> [--mono]
19
+ [--check] [--timeout-seconds <30..7200>]
20
+
21
+ --check validates tools, model hash, source and disk space; it creates no output.
22
+ --mono explicitly allows stereo downmix (0.5 L + 0.5 R). Mono needs no flag.
23
+ The first audio stream is used. Other multichannel layouts are unsupported.
24
+ Limit: one hour per invocation; default total process deadline: 1800 seconds.
25
+ Input/output paths must not contain symlinks. Output parent must already exist.
26
+ Output: cleaned-48k.wav (mono PCM16), report.json, inference.log.
27
+ No network, automatic installation, overwrite, loudness normalization or approval.
28
+ Install the external tools separately; this helper never uploads your recording.
29
+ `;
30
+
31
+ function fail(code, message) { const error = new Error(message); error.code = code; throw error; }
32
+
33
+ export function parseArgs(argv) {
34
+ const result = { mono: false, check: false, timeoutSeconds: 1800 };
35
+ const valueFlags = new Map([['--input', 'input'], ['--out', 'out'], ['--binary', 'binary'], ['--model', 'model'], ['--timeout-seconds', 'timeoutSeconds']]);
36
+ const seen = new Set();
37
+ for (let i = 0; i < argv.length; i++) {
38
+ const flag = argv[i];
39
+ if (flag === '--help' || flag === '-h') return { help: true };
40
+ if (seen.has(flag)) fail('invalid_argument', `Repeated option: ${flag}`);
41
+ seen.add(flag);
42
+ if (flag === '--mono' || flag === '--check') { result[flag.slice(2)] = true; continue; }
43
+ const key = valueFlags.get(flag);
44
+ if (!key || !argv[i + 1] || argv[i + 1].startsWith('--')) fail('invalid_argument', `Unknown option or missing value: ${flag}. Run --help.`);
45
+ result[key] = argv[++i];
46
+ }
47
+ for (const key of ['input', 'out', 'binary', 'model']) if (!result[key]) fail('missing_argument', `Missing --${key}. Run --help.`);
48
+ result.timeoutSeconds = Number(result.timeoutSeconds);
49
+ if (!Number.isInteger(result.timeoutSeconds) || result.timeoutSeconds < 30 || result.timeoutSeconds > 7200) fail('invalid_argument', '--timeout-seconds must be an integer from 30 to 7200.');
50
+ return result;
51
+ }
52
+
53
+ export async function sha256(file) {
54
+ const hash = createHash('sha256');
55
+ for await (const chunk of createReadStream(file)) hash.update(chunk);
56
+ return hash.digest('hex');
57
+ }
58
+
59
+ async function checkedPath(file, kind = 'file') {
60
+ const absolute = path.resolve(file);
61
+ let cursor = path.parse(absolute).root;
62
+ for (const part of absolute.slice(cursor.length).split(path.sep).filter(Boolean)) {
63
+ cursor = path.join(cursor, part);
64
+ let info;
65
+ try { info = await lstat(cursor); } catch (error) {
66
+ if (error.code === 'ENOENT') fail('path_missing', `Path does not exist: ${cursor}`);
67
+ throw error;
68
+ }
69
+ if (info.isSymbolicLink()) fail('symlink_not_allowed', `Symlink is not supported: ${cursor}. Use a regular local path.`);
70
+ }
71
+ const info = await lstat(absolute);
72
+ if (!(kind === 'directory' ? info.isDirectory() : info.isFile())) fail('invalid_path', `Expected a ${kind}: ${absolute}`);
73
+ return absolute;
74
+ }
75
+
76
+ async function newOutputPath(file) {
77
+ const absolute = path.resolve(file);
78
+ await checkedPath(path.dirname(absolute), 'directory');
79
+ try { await lstat(absolute); } catch (error) {
80
+ if (error.code === 'ENOENT') return absolute;
81
+ throw error;
82
+ }
83
+ fail('output_exists', `Output already exists: ${absolute}. Choose a new directory; nothing was overwritten.`);
84
+ }
85
+
86
+ async function findTool(name) {
87
+ for (const directory of (process.env.PATH ?? '').split(path.delimiter).filter(Boolean)) {
88
+ const candidate = path.resolve(directory, process.platform === 'win32' ? `${name}.exe` : name);
89
+ try { await access(candidate, constants.X_OK); return await realpath(candidate); } catch {}
90
+ }
91
+ fail('tool_missing', `${name} is missing from PATH. Install ffmpeg/ffprobe separately, then run --check again.`);
92
+ }
93
+
94
+ export function runProcess(command, args, timeoutMs) {
95
+ return new Promise((resolve, reject) => {
96
+ const child = spawn(command, args, { shell: false, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
97
+ let stdout = '', stderr = '', overflow = false, timedOut = false;
98
+ const collect = (current, chunk) => {
99
+ if (Buffer.byteLength(current) + chunk.length > MAX_LOG_BYTES) { overflow = true; child.kill('SIGKILL'); return current; }
100
+ return current + chunk.toString('utf8');
101
+ };
102
+ child.stdout.on('data', (chunk) => { stdout = collect(stdout, chunk); });
103
+ child.stderr.on('data', (chunk) => { stderr = collect(stderr, chunk); });
104
+ const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, timeoutMs);
105
+ child.once('error', (error) => { clearTimeout(timer); reject(error); });
106
+ child.once('close', (code, signal) => {
107
+ clearTimeout(timer);
108
+ if (timedOut || overflow || code !== 0) {
109
+ const error = new Error(`${path.basename(command)} ${timedOut ? 'timed out' : overflow ? 'exceeded the log limit' : `failed (${code ?? signal})`}. ${stderr.slice(-3000)}`);
110
+ error.code = timedOut ? 'process_timeout' : 'process_failed'; reject(error);
111
+ } else resolve({ stdout, stderr });
112
+ });
113
+ });
114
+ }
115
+
116
+ export async function pcmInfo(file) {
117
+ const handle = await open(file, 'r');
118
+ try {
119
+ const info = await handle.stat();
120
+ const header = Buffer.alloc(12); await handle.read(header, 0, 12, 0);
121
+ if (header.toString('ascii', 0, 4) !== 'RIFF' || header.toString('ascii', 8, 12) !== 'WAVE') fail('invalid_audio', `Expected RIFF WAV: ${file}`);
122
+ let offset = 12, format;
123
+ while (offset + 8 <= info.size) {
124
+ const chunk = Buffer.alloc(8); await handle.read(chunk, 0, 8, offset);
125
+ const name = chunk.toString('ascii', 0, 4), size = chunk.readUInt32LE(4);
126
+ const start = offset + 8;
127
+ if (start + size > info.size) fail('invalid_audio', `Truncated WAV chunk: ${file}`);
128
+ if (name === 'fmt ') {
129
+ if (size < 16) fail('invalid_audio', `Invalid WAV format: ${file}`);
130
+ const fmt = Buffer.alloc(16); await handle.read(fmt, 0, 16, start);
131
+ format = { codec: fmt.readUInt16LE(0), channels: fmt.readUInt16LE(2), rate: fmt.readUInt32LE(4), bits: fmt.readUInt16LE(14) };
132
+ }
133
+ if (name === 'data') {
134
+ if (!format || format.codec !== 1 || format.channels !== 1 || format.rate !== SAMPLE_RATE || format.bits !== 16 || size % 2 || !size) fail('invalid_audio', `Expected nonempty mono 48 kHz PCM16 WAV: ${file}`);
135
+ return { file, dataOffset: start, samples: size / 2, bytes: size };
136
+ }
137
+ offset = start + size + size % 2;
138
+ }
139
+ fail('invalid_audio', `WAV has no audio data: ${file}`);
140
+ } finally { await handle.close(); }
141
+ }
142
+
143
+ export function compensation(samples) {
144
+ const delay = 1440, hop = 480;
145
+ const paddedSamples = Math.ceil((samples + delay) / hop) * hop;
146
+ return { delay, hop, paddedSamples, paddingSamples: paddedSamples - samples, trimSamples: paddedSamples - delay - samples };
147
+ }
148
+
149
+ // Stream PCM so a one-hour recording never needs a full in-memory audio buffer.
150
+ export async function writePcm(file, source, samples, zeroSamples = 0) {
151
+ if (samples > source.samples || samples < 0 || zeroSamples < 0) fail('invalid_audio', 'PCM copy exceeds available samples.');
152
+ const header = Buffer.alloc(44), bytes = (samples + zeroSamples) * 2;
153
+ header.write('RIFF'); header.writeUInt32LE(36 + bytes, 4); header.write('WAVEfmt ', 8);
154
+ header.writeUInt32LE(16, 16); header.writeUInt16LE(1, 20); header.writeUInt16LE(1, 22);
155
+ header.writeUInt32LE(SAMPLE_RATE, 24); header.writeUInt32LE(SAMPLE_RATE * 2, 28); header.writeUInt16LE(2, 32); header.writeUInt16LE(16, 34);
156
+ header.write('data', 36); header.writeUInt32LE(bytes, 40);
157
+ const output = await open(file, 'wx', 0o600), input = await open(source.file, 'r');
158
+ try {
159
+ await output.writeFile(header);
160
+ const buffer = Buffer.alloc(65536);
161
+ for (let copied = 0; copied < samples * 2;) {
162
+ const length = Math.min(buffer.length, samples * 2 - copied);
163
+ const { bytesRead } = await input.read(buffer, 0, length, source.dataOffset + copied);
164
+ if (bytesRead !== length) fail('invalid_audio', 'Audio changed or ended during copy.');
165
+ await output.writeFile(buffer.subarray(0, bytesRead)); copied += bytesRead;
166
+ }
167
+ buffer.fill(0);
168
+ for (let remaining = zeroSamples * 2; remaining > 0;) {
169
+ const length = Math.min(remaining, buffer.length); await output.writeFile(buffer.subarray(0, length)); remaining -= length;
170
+ }
171
+ } finally { await input.close(); await output.close(); }
172
+ }
173
+
174
+ export async function runCleanup(options, dependencies = {}) {
175
+ // Dependency injection is only for local fault tests, never a CLI model-hash override.
176
+ const execute = dependencies.run ?? runProcess;
177
+ const expectedHash = dependencies.modelHash ?? MODEL_SHA256;
178
+ const started = performance.now(), deadline = Date.now() + options.timeoutSeconds * 1000;
179
+ const run = (command, args, maximumMs = Infinity) => {
180
+ const remaining = deadline - Date.now();
181
+ if (remaining <= 0) fail('process_timeout', 'Cleanup deadline exceeded. Increase --timeout-seconds explicitly.');
182
+ return execute(command, args, Math.min(remaining, maximumMs));
183
+ };
184
+ const input = await checkedPath(options.input), binary = await checkedPath(options.binary), model = await checkedPath(options.model);
185
+ const out = await newOutputPath(options.out);
186
+ const modelHash = await sha256(model);
187
+ if (modelHash !== expectedHash) fail('model_hash_mismatch', `Model SHA256 is ${modelHash}; expected official DeepFilterNet3 v0.5.6 ${expectedHash}. Download the exact model separately; no inference ran.`);
188
+ await access(binary, constants.X_OK).catch(() => fail('binary_not_executable', `Binary is not executable: ${binary}. Check its platform and executable permission.`));
189
+ const version = (await run(binary, ['--version'], 10000)).stdout.trim();
190
+ if (version !== 'deep_filter 0.5.6') fail('binary_version_mismatch', `Expected deep_filter 0.5.6; received ${JSON.stringify(version)}. Use the official matching binary.`);
191
+ const ffmpeg = dependencies.ffmpeg ?? await findTool('ffmpeg'), ffprobe = dependencies.ffprobe ?? await findTool('ffprobe');
192
+ let ffmpegVersion;
193
+ try {
194
+ ffmpegVersion = (await run(ffmpeg, ['-version'], 10000)).stdout.split('\n')[0].trim();
195
+ } catch (error) {
196
+ fail('tool_unavailable', `ffmpeg could not run: ${ffmpeg}. Check its platform and installation, then retry --check. ${error.message}`);
197
+ }
198
+ if (!/^ffmpeg version\s+\S+/.test(ffmpegVersion)) fail('tool_unavailable', `Unexpected ffmpeg version response from ${ffmpeg}. Install a working ffmpeg binary and retry --check.`);
199
+ let probe;
200
+ try { probe = JSON.parse((await run(ffprobe, ['-v', 'error', '-protocol_whitelist', 'file,pipe', '-select_streams', 'a:0', '-show_entries', 'stream=channels,sample_rate,duration,start_time:format=duration', '-of', 'json', input], 30000)).stdout); }
201
+ catch (error) { if (error.code) throw error; fail('probe_failed', `Cannot read audio metadata: ${error.message}`); }
202
+ const stream = probe.streams?.[0];
203
+ const streamDuration = Number(stream?.duration);
204
+ const duration = Number.isFinite(streamDuration) && streamDuration > 0 ? streamDuration : Number(probe.format?.duration);
205
+ if (!stream || !Number.isFinite(duration) || duration <= 0 || duration > MAX_SECONDS) fail('unsupported_audio', 'The first audio stream must have a known duration between 0 and 3600 seconds. Extract or split longer input explicitly.');
206
+ if (stream.channels !== 1 && !(stream.channels === 2 && options.mono)) fail('explicit_mono_required', `Input has ${stream.channels} channels. Stereo requires --mono to authorize 0.5 L + 0.5 R; other layouts are unsupported.`);
207
+ const decodeLimitSeconds = Math.min(MAX_SECONDS + 1, Math.ceil(duration) + 2);
208
+ const requiredBytes = Math.ceil((decodeLimitSeconds + 1) * SAMPLE_RATE * 2 * 4 + 64 * 1024 * 1024);
209
+ const disk = await statfs(path.dirname(out));
210
+ if (disk.bavail * disk.bsize < requiredBytes) fail('disk_space_required', `Need approximately ${requiredBytes} free bytes for bounded temporary audio files. Choose another local output directory.`);
211
+ const inputHash = await sha256(input), binaryHash = await sha256(binary);
212
+ if (options.check) return { ok: true, mode: 'check', engine: 'DeepFilterNet3', binaryVersion: version, ffmpegVersion, modelSha256: modelHash, inputSha256: inputHash, inputChannels: stream.channels, monoDownmix: stream.channels === 2, durationSeconds: duration, estimatedTemporaryBytes: requiredBytes, output: out, inferenceRan: false };
213
+ await mkdir(out, { mode: 0o700 });
214
+ try {
215
+ const temp = path.join(out, '.working'); await mkdir(temp, { mode: 0o700 });
216
+ const decoded = path.join(temp, 'input.wav'), padded = path.join(temp, 'padded.wav'), processedDir = path.join(temp, 'processed');
217
+ const filters = stream.channels === 2 ? ['-af', 'pan=mono|c0=0.5*c0+0.5*c1'] : [];
218
+ // Limit decoding too: inaccurate container metadata cannot fill the disk indefinitely.
219
+ await run(ffmpeg, ['-hide_banner', '-loglevel', 'error', '-nostdin', '-n', '-protocol_whitelist', 'file,pipe', '-i', input, '-map', '0:a:0', '-vn', ...filters, '-t', String(decodeLimitSeconds), '-ar', '48000', '-c:a', 'pcm_s16le', '-map_metadata', '-1', decoded]);
220
+ const original = await pcmInfo(decoded);
221
+ if (original.samples >= decodeLimitSeconds * SAMPLE_RATE) fail('duration_metadata_mismatch', 'Audio exceeded its declared duration. Refusing to publish a truncated result; repair or extract the source explicitly.');
222
+ if (original.samples > MAX_SECONDS * SAMPLE_RATE) fail('unsupported_audio', 'Decoded audio exceeds one hour. Split the source explicitly.');
223
+ const timing = compensation(original.samples);
224
+ await writePcm(padded, original, original.samples, timing.paddingSamples);
225
+ const inferStart = performance.now();
226
+ const inference = await run(binary, ['--model', model, '--compensate-delay', '-vv', '--output-dir', processedDir, padded]);
227
+ const inferenceWallSeconds = (performance.now() - inferStart) / 1000;
228
+ const log = inference.stdout + inference.stderr;
229
+ if (!/model type deepfilternet3\b/.test(log)) fail('model_not_confirmed', 'Runtime did not confirm deepfilternet3. Output was not published.');
230
+ const processed = await pcmInfo(path.join(processedDir, 'padded.wav'));
231
+ if (processed.samples !== timing.paddedSamples - timing.delay) fail('sample_count_mismatch', `Expected ${timing.paddedSamples - timing.delay} processed samples; got ${processed.samples}. Output was not published.`);
232
+ const cleaned = path.join(out, 'cleaned-48k.wav');
233
+ await writePcm(cleaned, processed, original.samples);
234
+ if (await sha256(input) !== inputHash || await sha256(model) !== modelHash || await sha256(binary) !== binaryHash) fail('input_changed', 'Source, model or binary changed while running. Output was not published.');
235
+ const report = { schemaVersion: 1, ok: true, engine: 'DeepFilterNet3', externalTool: true, binaryVersion: version, binarySha256: binaryHash, modelSha256: modelHash, input: { path: input, sha256: inputHash, selectedAudioStream: '0:a:0', channels: stream.channels, sampleRate: Number(stream.sample_rate) || null, startTimeSeconds: Number.isFinite(Number(stream.start_time)) ? Number(stream.start_time) : null, decodedSamplesAt48k: original.samples }, output: { path: cleaned, sha256: await sha256(cleaned), channels: 1, sampleRate: SAMPLE_RATE, format: 'PCM16', samples: original.samples, durationSeconds: original.samples / SAMPLE_RATE }, processing: { monoDownmix: stream.channels === 2 ? '0.5 L + 0.5 R (explicit --mono)' : null, normalization: 'none', postfilter: false, attenuationLimitDb: 100, stftFftSamples: 960, hopSamples: timing.hop, lookaheadHops: 2, compensatedLatencySamples: timing.delay, inputPaddingSamples: timing.paddingSamples, outputTailTrimSamples: timing.trimSamples }, timing: { inferenceProcessSeconds: inferenceWallSeconds, totalSeconds: (performance.now() - started) / 1000 }, quality: 'not_assessed', approval: 'not_granted', originalPreserved: true, notes: ['Source audio was resampled to 48 kHz when necessary; input file is unchanged.', 'Padding flushes the model tail before exact sample-count trimming.', 'When remuxing video, align this WAV with the selected source audio stream start time; the helper does not edit video.', 'Listen for missing consonants, altered timbre and remaining background voices. Structural success does not certify audio quality.', 'No loudness normalization, upload, installation or payment was performed.'] };
236
+ await writeFile(path.join(out, 'inference.log'), log, { flag: 'wx', mode: 0o600 });
237
+ await writeFile(path.join(out, 'report.json'), JSON.stringify(report, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
238
+ await rm(temp, { recursive: true });
239
+ return report;
240
+ } catch (error) {
241
+ await rm(out, { recursive: true, force: true });
242
+ throw error;
243
+ }
244
+ }
245
+
246
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
247
+ try {
248
+ const options = parseArgs(process.argv.slice(2));
249
+ if (options.help) process.stdout.write(HELP);
250
+ else process.stdout.write(JSON.stringify(await runCleanup(options), null, 2) + '\n');
251
+ } catch (error) {
252
+ process.stderr.write(JSON.stringify({ ok: false, code: error.code ?? 'cleanup_failed', message: error.message }) + '\n');
253
+ process.exitCode = 1;
254
+ }
255
+ }