Files
hyperframes/packages/cli/src/commands/remove-background.ts
T
James RussoandClaude Opus 5.5 943b6512b4 feat(cli): add hyperframes/api entry with transcribe and removeBackground (#5453)
* feat(cli): add hyperframes/api entry with transcribe and removeBackground

HyperFrames Desktop runs the CLI as a child process, relaunching Electron
with ELECTRON_RUN_AS_NODE=1. A programmatic entry lets it import plain
functions and run them in a utilityProcess instead, so the RunAsNode fuse
can be turned off.

packages/cli/src/api.ts exports transcribe() and removeBackground(): typed
options in, typed result out, progress through callbacks, failures thrown
as TranscribeError / RemoveBackgroundError with a code and the original
error as cause. Neither prints, reads argv or exits.

The transcribe and remove-background commands now keep only flag
handling, printing and exit codes, and call these functions. Their
output, JSON and exit codes are unchanged.

The package gains an exports map with "./api" (built dist plus d.ts) and
"./package.json", generated from package-subpaths.json like the sibling
packages.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(cli): trim api.ts comments under the package's comment share

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(cli): trim trailing dots without a quadratic regex

CodeQL flags the trailing-dots regex on the Parakeet error now that it sits
behind a library entry. Same result, linear time.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(cli): make the transcribe API's signal stop every stage

Review follow-ups on the api entry:

- parakeet-mlx now runs as an async child that the caller's signal can
  kill. Its failures keep the synchronous run's message, status and stderr.
- A pre-aborted signal throws before any setup. Whisper checks the signal
  before each setup stage, and the model download gets it.
- onEngine reports the model whisper runs (small for Spanish, not small.en).
  The resolver moved to whisper/modelForLanguage.ts so both share it.
- api/transcribe.ts imports everything at module scope. The command test
  hoists its whisper mock, since that module now loads during imports.
- whisper's internal TranscribeOptions/TranscribeResult types are renamed
  WhisperOptions/RunnerResult, so the API's public names are unique.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(cli): let an AbortSignal stop whisper's install and audio prep

Review follow-ups on the api entry:

- whisper's runtime install (brew, git clone, cmake) and its ffmpeg audio
  prep run through a new stoppableExecFile when an API caller passes a
  signal. The child runs off the event loop, an abort ends it and every
  process it started, and the call rejects with a "cancelled"
  TranscribeError once they are gone. A failure throws the same error
  execFileSync throws (message, code, errno, status, signal, stdout,
  stderr), compared field by field in stoppableExecFile.test.ts.
  parakeet-mlx uses the same helper.
- Without a signal the helper is execFileSync, and the CLI passes none, so
  the CLI output stays byte for byte the same as hyperframes 0.8.146.
- TranscribeOptions.signal now says what it covers: a tool lookup that is
  already running (capped at 10 seconds) finishes first.
- New regressions in api.test.ts abort during a stand-in install step and
  during a stand-in ffmpeg convert. Both end in under 10 seconds with no
  process left, and both fail with the old synchronous calls.
- Tests load every module at the top of the file: namespace spies replace
  the importOriginal partial mocks, and node:fs and node:child_process are
  spied through their default exports and synced with
  syncBuiltinESMExports. remove-background --info imports its manager
  statically. The scanner in api.test.ts now reads every file this PR
  touches and catches importOriginal and vi.importActual.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-11 18:05:11 +00:00

226 lines
8.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { failCommand } from "../utils/commandResult.js";
import { defineCommand } from "citty";
import { existsSync } from "node:fs";
import * as clack from "@clack/prompts";
import { c } from "../ui/colors.js";
import {
DEFAULT_MODEL,
DEVICES,
MODEL_MEMORY_MB,
isDevice,
listAvailableProviders,
modelPath,
selectProviders,
} from "../background-removal/manager.js";
import { DEFAULT_QUALITY, QUALITIES, isQuality } from "../background-removal/pipeline.js";
import type { Example } from "./_examples.js";
import { RemoveBackgroundError, removeBackground } from "../api/removeBackground.js";
export const examples: Example[] = [
[
"Remove background from a video, output transparent VP9 WebM (default)",
"hyperframes remove-background avatar.mp4 -o transparent.webm",
],
[
"Output ProRes 4444 .mov for editing round-trip",
"hyperframes remove-background avatar.mp4 -o transparent.mov",
],
[
"Remove background from a single image, output transparent PNG",
"hyperframes remove-background portrait.jpg -o cutout.png",
],
[
"Separate the layers — emit both the cutout and an inverse-alpha background plate (subject region transparent)",
"hyperframes remove-background avatar.mp4 -o subject.webm --background-output plate.webm",
],
[
"Force CPU (skip CoreML/CUDA)",
"hyperframes remove-background avatar.mp4 -o transparent.webm --device cpu",
],
[
"Smaller file at the cost of color match (text-behind-subject won't blend as cleanly)",
"hyperframes remove-background avatar.mp4 -o transparent.webm --quality fast",
],
[
"Visually-lossless WebM (master / re-encode source)",
"hyperframes remove-background avatar.mp4 -o transparent.webm --quality best",
],
["Show detected providers without rendering", "hyperframes remove-background --info"],
];
export default defineCommand({
meta: {
name: "remove-background",
description:
"Remove background from a video or image using a local AI model — outputs transparent WebM, ProRes 4444, or PNG",
},
args: {
input: {
type: "positional",
description: "Source video (.mp4/.mov/.webm/.mkv) or image (.jpg/.png/.webp)",
required: false,
},
output: {
type: "string",
description: "Output path. Format inferred from extension: .webm (default), .mov, .png",
alias: "o",
},
"background-output": {
type: "string",
description:
"Optional second output path for the inverse-alpha background plate (subject region transparent, original surroundings opaque). Hole-cut, not inpainted — composite something underneath to fill the hole. Must be .webm or .mov; not allowed for image inputs.",
alias: "b",
},
device: {
type: "string",
description: `Execution provider: ${DEVICES.join(", ")}`,
default: "auto",
},
quality: {
type: "string",
description: `Encoder quality preset for .webm output: ${QUALITIES.join(", ")} (default: ${DEFAULT_QUALITY}). Higher quality = closer color match when overlaying on the source mp4, larger file. Ignored for .mov / .png.`,
default: DEFAULT_QUALITY,
},
info: {
type: "boolean",
description: "Print detected execution providers and exit (no render)",
default: false,
},
json: {
type: "boolean",
description: "Output result as JSON",
default: false,
},
},
async run({ args }) {
if (args.info) {
return showInfo(args.json);
}
if (!args.input) {
console.error(
c.error(
"Input file is required. Run `hyperframes remove-background --info` for providers.",
),
);
failCommand();
}
if (!args.output) {
console.error(c.error("--output (-o) is required. Use a .webm, .mov, or .png path."));
failCommand();
}
if (!isDevice(args.device)) {
console.error(
c.error(`Invalid --device '${String(args.device)}'. Use: ${DEVICES.join(", ")}.`),
);
failCommand();
}
if (!isQuality(args.quality)) {
console.error(
c.error(`Invalid --quality '${String(args.quality)}'. Use: ${QUALITIES.join(", ")}.`),
);
failCommand();
}
const spin = args.json ? null : clack.spinner();
spin?.start("Preparing background-removal pipeline...");
try {
const result = await removeBackground({
input: args.input,
output: args.output,
backgroundOutput: args["background-output"],
device: args.device,
quality: args.quality,
onProgress: (event) => {
if (event.kind === "info") {
spin?.message(event.message);
} else if (event.kind === "metadata") {
const dims = `${event.width}×${event.height}`;
const frames = event.frameCount ? ` · ${event.frameCount} frames` : "";
spin?.message(`Source ${dims} @ ${event.fps.toFixed(0)}fps${frames}`);
} else if (event.kind === "frame") {
const pct = event.total ? ` (${Math.floor((100 * event.index) / event.total)}%)` : "";
spin?.message(
`Frame ${event.index}${event.total ? `/${event.total}` : ""}${pct} — ${Math.round(event.avgMsPerFrame)}ms/frame avg`,
);
}
},
});
if (args.json) {
console.log(
JSON.stringify({
ok: true,
outputPath: result.outputPath,
...(result.backgroundOutputPath
? { backgroundOutputPath: result.backgroundOutputPath }
: {}),
framesProcessed: result.framesProcessed,
durationSeconds: Number(result.durationSeconds.toFixed(2)),
avgMsPerFrame: Number(result.avgMsPerFrame.toFixed(1)),
provider: result.provider,
format: result.format,
}),
);
} else {
const fpsThroughput = result.durationSeconds
? (result.framesProcessed / result.durationSeconds).toFixed(1)
: "n/a";
const outputs = result.backgroundOutputPath
? `${c.accent(result.outputPath)} + ${c.accent(result.backgroundOutputPath)}`
: c.accent(result.outputPath);
spin?.stop(
c.success(
`Removed background from ${c.accent(String(result.framesProcessed))} frames in ${result.durationSeconds.toFixed(1)}s (${fpsThroughput} fps, ${c.accent(result.provider)}) → ${outputs}`,
),
);
}
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
if (args.json) {
console.log(JSON.stringify({ ok: false, error: message }));
} else {
spin?.stop(c.error(`Background removal failed: ${message}`));
}
failCommand(1, pipelineError(err));
}
},
});
/** The pipeline's own error, which the command reported before the API wrapped it. */
function pipelineError(err: unknown): unknown {
return err instanceof RemoveBackgroundError ? err.cause : err;
}
async function showInfo(json: boolean): Promise<void> {
const providers = listAvailableProviders();
const auto = selectProviders("auto");
const cached = existsSync(modelPath());
if (json) {
console.log(
JSON.stringify({
defaultModel: DEFAULT_MODEL,
modelCached: cached,
modelPath: modelPath(),
peakMemoryMb: MODEL_MEMORY_MB[DEFAULT_MODEL],
availableProviders: providers,
autoProvider: auto.label,
}),
);
return;
}
console.log(c.bold("hyperframes remove-background — system info"));
console.log("");
console.log(` ${c.dim("Default model:")} ${c.accent(DEFAULT_MODEL)}`);
console.log(` ${c.dim("Peak memory:")} ~${MODEL_MEMORY_MB[DEFAULT_MODEL]} MB`);
console.log(
` ${c.dim("Weights cached:")} ${cached ? c.success("yes") : c.dim("no (will download on first run)")}`,
);
console.log(` ${c.dim("Cache path:")} ${modelPath()}`);
console.log("");
console.log(` ${c.dim("Available providers:")} ${providers.join(", ")}`);
console.log(` ${c.dim("Auto-selected:")} ${c.accent(auto.label)}`);
}