@video-ultra/ai
Optional AI helpers: on-device background removal, speech detection and server endpoints.
npm install @video-ultra/aiFunctions
alignWords
functionTimes words from the sound they were heard in, for a speech service that gives the words but no usable times (Gemini's drift by seconds over 30 s). The voice is where the sound is loud enough (20 ms frames, gaps under 200 ms filled); words share it by length (a digit counts as a few letters: "15" is said "fifteen"). A phrase end (punctuation) is pinned to the nearest real pause when one is within 1.5 s of voice, so sentences start when the speaker does. Measured against the on-device model's times: 0.14–0.25 s mean error on three English clips (one over music), where Gemini's own were off by up to 11 s.
function alignWords(words: readonly string[], audio: Float32Array, voice?: Uint8Array): TranscriptWord[];chooseBackgroundModel
functionThe model for this device: objects (any subject, cleaner edges; +0.7 GB while it works) on computers, people (+0.26 GB) on phones and tablets (a touch screen as the main pointer) and wherever the device says it has under 4 GB. Browser APIs are read here, never at import time (SSR safe).
function chooseBackgroundModel(model?: BackgroundModel | 'auto'): BackgroundModel;createBackgroundRemover
functionAn on-device BackgroundRemover: one worker per picture, closed when it's done.
function createBackgroundRemover(options?: BackgroundRemoverOptions): BackgroundRemover;createCaptionsEndpoint
functionA Transcriber for your own captions endpoint: any speech service, any language, with the key on your server. Sends the sound in pieces of up to 30 s, cut where it's quietest (no word cut in two; silent pieces aren't sent), up to three at once (one while the service is busy), and turns the replies into timed words: words said in the silence before speech move onto it, made-up and doubtful words are dropped. Detect decides the language from the first pieces with speech and asks for it from then on. When the service's own word times stop well before a piece ends while people still speak, the rest of the piece is asked for once more.
import { createCaptionsEndpoint } from '@video-ultra/ai';
<VideoEditor transcriber={createCaptionsEndpoint({ endpoint: '/api/captions' })} />function createCaptionsEndpoint(options: CaptionsEndpointOptions): Transcriber;createChatAssistant
functionAn EditingAssistant for any OpenAI-compatible chat endpoint (v0.4). Sends the instruction, the project description and the action guide; expects JSON {reply, actions} back. The editor validates every action before applying (one undo step).
import { createChatAssistant } from '@video-ultra/ai';
<VideoEditor assistant={createChatAssistant({ endpoint: '/api/assistant' })} />function createChatAssistant(options: ChatAssistantOptions): EditingAssistant;createSpeechDetector
functionA speech detector running in a worker: Silero VAD (MIT, 0.64 MB, downloaded once and cached). Measured: speech found 98–100 % with music or fan noise as loud as the voice (judging by loudness found 0–14 %), music or noise alone never taken for speech; ~0.1 s per 22 s of sound. createCaptionsEndpoint uses one by default.
function createSpeechDetector(options?: SpeechDetectorOptions): SpeechDetector;createSpeechEndpoint
functionA SpeechGenerator for OpenAI-compatible /audio/speech endpoints (v0.4).
import { createSpeechEndpoint } from '@video-ultra/ai';
<VideoEditor speech={createSpeechEndpoint({ endpoint: '/api/speech' })} />function createSpeechEndpoint(options: SpeechEndpointOptions): SpeechGenerator;parseAnswer
functionReads a model's answer: JSON (possibly in a `` block) with reply and actions`.
function parseAnswer(text: string): EditingResponse;Types
BackgroundModel
typeWhich model: people (small, fast, best on people) or objects (anything; bigger).
type BackgroundModel = 'people' | 'objects';Options of createBackgroundRemover.
interface BackgroundRemoverOptions {
/** Default `auto`: see {@link chooseBackgroundModel}. */
model?: BackgroundModel | 'auto';
/**
* Where model files come from — self-host them by mirroring the model repos (files are
* fetched from `<modelHost>/<repo>/resolve/main/onnx/<file>`). Default `https://huggingface.co`.
*/
modelHost?: string;
/** Where the runtime's `.wasm` files are served (default: next to its JS module). */
runtimePath?: string;
/** Longest side of the result in pixels (default 4096; bigger photos are scaled down). */
maxSide?: number;
}Options of createCaptionsEndpoint.
interface CaptionsEndpointOptions {
/**
* Your captions endpoint — your own server, which calls whichever speech service you use and
* keeps its key (see {@link CaptionsEndpointReply} for what it receives and answers).
*/
endpoint: string;
/**
* Languages your service hears (ISO 639-1), plus `'auto'` if it can detect the language; the
* Captions panel offers exactly these. Default: the panel's own list and Detect.
*/
languages?: readonly string[];
/** Extra request headers (e.g. your app's session token). */
headers?: Record<string, string>;
/** Roughly how many seconds of speech it captions per second, for "about N min". Default 8. */
speed?: number;
/** Pieces sent at once on long videos (one while the service is busy). Default 3. */
parallel?: number;
/**
* How to find where people speak in a piece. `'detector'` (default where workers run): a small
* speech detector on the device (`createSpeechDetector`) — tells speech from music and noise;
* `'loudness'`: by loudness only (no download); or your own (one byte per 20 ms, 1 = speech).
*/
voice?: 'detector' | 'loudness' | ((sound: Float32Array) => Promise<Uint8Array> | Uint8Array);
/** Where the speech detector's model and runtime come from (see `createSpeechDetector`). */
detector?: SpeechDetectorOptions;
/** For tests / custom transports. Default: the global `fetch`. */
fetch?: typeof fetch;
/**
* First wait before trying a busy service again (ms), doubling each time, four tries more;
* a `Retry-After` header from your endpoint wins. Default 3000.
*/
retryWait?: number;
}What your endpoint answers for one piece of sound. It receives a POST to <endpoint>?language=<code> (an ISO 639-1 code; hi-Latn for Hinglish — Hindi in Latin letters, as people type it; or auto to detect) whose body is the sound: 32-bit float samples, little-endian, 16 kHz, mono, at most 31 s (application/octet-stream). Optional query parameters, to pass on to your service as a hint (e.g. Whisper's prompt): context — the last words said before this piece; vocabulary — names and words that may be said, comma-separated.
interface CaptionsEndpointReply {
/**
* The words said, in order, with punctuation. Give each `start` / `end` (seconds from the start
* of this piece) when your service has them — the word-by-word highlight follows them. Without
* times (plain strings, or objects without them) the words are timed from the sound itself,
* which is close on steady speech but less exact. `confidence` (0…1), when your service has
* one: words under 0.3 are dropped (likely made up), captions averaging under 0.6 are marked
* for the person to check.
*/
words: (string | {
text: string;
start?: number;
end?: number;
confidence?: number;
})[];
/**
* The language actually spoken (ISO 639-1). When it isn't the one asked for, answer the words
* you have (or none): if no piece was in the chosen language, the editor says which language
* it heard instead of making captions.
*/
language: string;
}Options of createChatAssistant.
interface ChatAssistantOptions {
/**
* An OpenAI-compatible chat completions URL — your own server or proxy, so API keys never
* reach the browser (e.g. `/api/assistant`, which adds the key and forwards).
*/
endpoint: string;
/** Model name sent as `model` (your endpoint may ignore it). */
model?: string;
/** Extra request headers (e.g. your app's session token). */
headers?: Record<string, string>;
/** Extra instructions after the built-in ones (house style, language…). */
instructions?: string;
/** For tests / custom transports. Default: the global `fetch`. */
fetch?: typeof fetch;
}SpeechDetector
typeFinds where people speak (as opposed to music or noise), on the device.
interface SpeechDetector {
/** One byte per 20 ms of 16 kHz mono `sound`: 1 = speech. */
detect(sound: Float32Array): Promise<Uint8Array>;
/** Closes its worker (its memory goes back); the next `detect` starts a new one. */
close(): void;
}Options of createSpeechDetector.
interface SpeechDetectorOptions {
/**
* Where the model comes from — self-host it by mirroring the repo: the file is fetched from
* `<modelHost>/onnx-community/silero-vad/resolve/main/onnx/model_quantized.onnx`.
* Default `https://huggingface.co`.
*/
modelHost?: string;
/** Where the runtime's `.wasm` files are served (default: next to its JS module). */
runtimePath?: string;
}Options of createSpeechEndpoint.
interface SpeechEndpointOptions {
/**
* An OpenAI-compatible `/audio/speech` URL — your own server or proxy (it adds the key), a
* hosted service, or a self-hosted open voice model with that API.
*/
endpoint: string;
/** Model name sent as `model`. */
model?: string;
/** The voices to offer. Default: the six common OpenAI-style voice ids. */
voices?: SpeechVoice[];
/** Audio format asked for (default `mp3`). */
format?: 'mp3' | 'wav' | 'opus' | 'aac' | 'flac';
headers?: Record<string, string>;
/**
* Whether the service honours the OpenAI-style `speed` field (default `true`). Set `false` for
* one that ignores it: the editor then sends speed 1 and plays the clip at the chosen speed,
* keeping the voice's pitch.
*/
appliesSpeed?: boolean;
/** For tests / custom transports. */
fetch?: typeof fetch;
}