16 lines
1.3 KiB
JavaScript
16 lines
1.3 KiB
JavaScript
import { mkdir, stat } from 'node:fs/promises';
|
|
import path from 'node:path';
|
|
import { spawn } from 'node:child_process';
|
|
|
|
export const MAX_LONG_EDGE = 1280;
|
|
|
|
export class FrameNormalizer {
|
|
constructor({ helper = path.resolve(new URL('./py/normalize_frame.py', import.meta.url).pathname), python = 'python3', spawnImpl = spawn, tmpDir = '/tmp/jarvis-cu', maxLongEdge = MAX_LONG_EDGE, quality = 70 } = {}) { this.helper = helper; this.python = python; this.spawnImpl = spawnImpl; this.tmpDir = tmpDir; this.maxLongEdge = maxLongEdge; this.quality = quality; }
|
|
async normalize(input, output = path.join(this.tmpDir, `frame-${Date.now()}.webp`), rect) {
|
|
await mkdir(path.dirname(output), { recursive: true });
|
|
const crop = rect ? rect.map(Number).map((value) => String(Math.round(value))) : [];
|
|
await new Promise((resolve, reject) => { const child = this.spawnImpl(this.python, [this.helper, input, output, String(this.maxLongEdge), String(this.quality), ...crop], { stdio: ['ignore', 'pipe', 'pipe'] }); let error = ''; child.stderr?.on('data', (d) => { error += d; }); child.on('error', reject); child.on('close', (code) => code === 0 ? resolve() : reject(new Error(error || `frame normalization exited ${code}`))); });
|
|
const info = await stat(output); return { path: output, bytes: info.size, maxLongEdge: this.maxLongEdge, mime: 'image/webp' };
|
|
}
|
|
}
|