license import * as tfc from '@tensorflow/tfjs-core' ; import { isArray , isNullOrUndefined } from 'util' ; import { NodeJSKernelBackend } from '../nodejs_kernel_backend' ; import { TFEOpAttr } from '../tfjs_binding' ; let gBackend = null ; /** Returns an instance of the Node.js backend. */ export function nodeBackend ( ) { if ( gBackend === null ) { gBackend = ( tfc . findBackend ( 'tensorflow' ) as NodeJSKernelBackend ) ; } return gBackend ; } /** Returns the TF dtype for a given DataType. */ export function getTFDType ( dataType ) { const binding = nodeBackend ( ) . binding ; switch ( dataType ) { case 'float32' : return binding . TF_FLOAT ; case 'int32' : return binding . TF_INT32 ; case 'bool' : return binding . TF_BOOL ; case 'complex64' : return binding . TF_COMPLEX64 ; case 'string' : return binding . TF_STRING ; case 'int64' as any : return binding . TF_INT64 ; default : const errorMessage = `Unknown dtype: ${ dataType }` ; throw new Error ( errorMessage ) ; } } deprecated export function createTypeOpAttr ( attrName , dtype ) { return { name : attrName , type : nodeBackend ( ) . binding . TF_ATTR_TYPE , value : getTFDType ( dtype ) } ; } /**
 * Creates a TFEOpAttr for a 'type' OpDef attribute from a Tensor or list of
 * Tensors.
 */ export function createTensorsTypeOpAttr ( attrName , tensors ) { if ( isNullOrUndefined ( tensors ) ) { throw new Error ( 'Invalid input tensors value.' ) ; } return { name : attrName , type : nodeBackend ( ) . binding . TF_ATTR_TYPE , value : getTFDTypeForInputs ( tensors ) } ; } /** Returns the dtype number for a single or list of input Tensors. */ function getTFDTypeForInputs ( tensors ) { if ( isNullOrUndefined ( tensors ) ) { throw new Error ( 'Invalid input tensors value.' ) ; } if ( isArray ( tensors ) ) { for ( let i = 0 ; i < tensors . length ; i ++ ) { return getTFDType ( tensors [ i ] . dtype ) ; } return - 1 ; } else { return getTFDType ( tensors . dtype ) ; } } export function ensureTensorflowBackend ( ) { if ( gBackend === null ) { nodeBackend ( ) ; } tfc . util . assert ( tfc . getBackend ( ) === 'tensorflow' , ( ) => `Expect the current backend to be "tensorflow", but got "${ tfc . getBackend ( ) }"` ) ; }