Adds a public function for creating TaskRunner instances.

PiperOrigin-RevId: 493109736
This commit is contained in:
MediaPipe Team 2022-12-05 14:14:13 -08:00 committed by Copybara-Service
parent 4f8eaee20f
commit 69b27b246a

View File

@ -32,6 +32,34 @@ const GraphRunnerImageLibType =
/** An implementation of the GraphRunner that supports image operations */
export class GraphRunnerImageLib extends GraphRunnerImageLibType {}
/**
* Creates a new instance of a Mediapipe Task. Determines if SIMD is
* supported and loads the relevant WASM binary.
* @return A fully instantiated instance of `T`.
*/
export async function
createTaskRunner<T extends TaskRunner<O>, O extends TaskRunnerOptions>(
type: WasmMediaPipeConstructor<T>, initializeCanvas: boolean,
fileset: WasmFileset, options: O): Promise<T> {
const fileLocator: FileLocator = {
locateFile() {
// The only file loaded with this mechanism is the Wasm binary
return fileset.wasmBinaryPath.toString();
}
};
// Initialize a canvas if requested. If OffscreenCanvas is availble, we
// let the graph runner initialize it by passing `undefined`.
const canvas = initializeCanvas ? (typeof OffscreenCanvas === 'undefined' ?
document.createElement('canvas') :
undefined) :
null;
const instance = await createMediaPipeLib(
type, fileset.wasmLoaderPath, NO_ASSETS, canvas, fileLocator);
await instance.setOptions(options);
return instance;
}
/** Base class for all MediaPipe Tasks. */
export abstract class TaskRunner<O extends TaskRunnerOptions> {
protected abstract baseOptions: BaseOptionsProto;
@ -47,23 +75,7 @@ export abstract class TaskRunner<O extends TaskRunnerOptions> {
O extends TaskRunnerOptions>(
type: WasmMediaPipeConstructor<T>, initializeCanvas: boolean,
fileset: WasmFileset, options: O): Promise<T> {
const fileLocator: FileLocator = {
locateFile() {
// The only file loaded with this mechanism is the Wasm binary
return fileset.wasmBinaryPath.toString();
}
};
// Initialize a canvas if requested. If OffscreenCanvas is availble, we
// let the graph runner initialize it by passing `undefined`.
const canvas = initializeCanvas ? (typeof OffscreenCanvas === 'undefined' ?
document.createElement('canvas') :
undefined) :
null;
const instance = await createMediaPipeLib(
type, fileset.wasmLoaderPath, NO_ASSETS, canvas, fileLocator);
await instance.setOptions(options);
return instance;
return createTaskRunner(type, initializeCanvas, fileset, options);
}
constructor(