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' } = {}) { this.helper = helper; this.python = python; this.spawnImpl = spawnImpl; this.tmpDir = tmpDir; } 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(MAX_LONG_EDGE), '70', ...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: MAX_LONG_EDGE, mime: 'image/webp' }; } }