2026-04-13 19:40:55 +08:00
|
|
|
import { readFile, writeFile } from "node:fs/promises";
|
|
|
|
|
import { join } from "node:path";
|
2026-04-21 23:54:25 +08:00
|
|
|
import sharp from "sharp";
|
2026-07-21 23:18:50 +08:00
|
|
|
import {
|
|
|
|
|
type ProgressCallback,
|
|
|
|
|
parseStdoutJson,
|
|
|
|
|
runPythonWithProgress,
|
|
|
|
|
toSidecarError,
|
|
|
|
|
} from "./bridge.js";
|
2026-04-13 19:40:55 +08:00
|
|
|
|
|
|
|
|
export interface ColorizeOptions {
|
|
|
|
|
intensity?: number;
|
|
|
|
|
model?: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export interface ColorizeResult {
|
|
|
|
|
buffer: Buffer;
|
|
|
|
|
width: number;
|
|
|
|
|
height: number;
|
|
|
|
|
method: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function colorize(
|
|
|
|
|
inputBuffer: Buffer,
|
|
|
|
|
outputDir: string,
|
|
|
|
|
options: ColorizeOptions = {},
|
|
|
|
|
onProgress?: ProgressCallback,
|
|
|
|
|
): Promise<ColorizeResult> {
|
|
|
|
|
const inputPath = join(outputDir, "input_colorize.png");
|
|
|
|
|
const outputPath = join(outputDir, "output_colorize.png");
|
|
|
|
|
|
2026-04-21 23:54:25 +08:00
|
|
|
const pngBuffer = await sharp(inputBuffer).png().toBuffer();
|
|
|
|
|
await writeFile(inputPath, pngBuffer);
|
2026-04-13 19:40:55 +08:00
|
|
|
const { stdout } = await runPythonWithProgress(
|
|
|
|
|
"colorize.py",
|
|
|
|
|
[inputPath, outputPath, JSON.stringify(options)],
|
|
|
|
|
{ onProgress },
|
|
|
|
|
);
|
|
|
|
|
|
2026-04-19 12:13:26 +08:00
|
|
|
const result = parseStdoutJson(stdout);
|
2026-04-13 19:40:55 +08:00
|
|
|
if (!result.success) {
|
2026-07-21 23:18:50 +08:00
|
|
|
throw toSidecarError(result.error, "Colorization failed");
|
2026-04-13 19:40:55 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const actualOutputPath = result.output_path || outputPath;
|
|
|
|
|
const buffer = await readFile(actualOutputPath);
|
|
|
|
|
return {
|
|
|
|
|
buffer,
|
|
|
|
|
width: result.width,
|
|
|
|
|
height: result.height,
|
|
|
|
|
method: result.method ?? "unknown",
|
|
|
|
|
};
|
|
|
|
|
}
|