license import * as tf from '@tensorflow/tfjs-core' ; import * as fs from 'fs' ; import { dirname , join , resolve } from 'path' ; /**
 * Handler for loading model files from local file system.
 */ export class FileHandler implements tf . io . IOHandler { protected readonly path : string ; param path constructor ( path ) { this . path = resolve ( path ) ; } return async load ( ) { const path = this . path ; const fsInfo = fs . statSync ( path ) ; if ( ! fsInfo . isFile ( ) ) { throw new Error ( 'The path to load from must be a file. Loading from a directory ' + 'is not supported.' ) ; } else { const file = fs . readFileSync ( path , 'utf8' ) ; const modelJSON = JSON . parse ( file ) ; const modelArtifacts = { modelTopology : modelJSON . modelTopology , format : modelJSON . format , generatedBy : modelJSON . generatedBy , convertedBy : modelJSON . convertedBy } ; if ( modelJSON . signature != null ) { modelArtifacts . signature = modelJSON . signature ; } if ( modelJSON . userDefinedMetadata != null ) { modelArtifacts . userDefinedMetadata = modelJSON . userDefinedMetadata ; } if ( modelJSON . modelInitializer != null ) { modelArtifacts . modelInitializer = modelJSON . modelInitializer ; } if ( modelJSON . weightsManifest != null ) { const [ weightSpecs , weightData ] = this . loadWeights ( modelJSON . weightsManifest , path ) ; modelArtifacts . weightSpecs = weightSpecs ; modelArtifacts . weightData = weightData ; } if ( modelJSON . trainingConfig != null ) { modelArtifacts . trainingConfig = modelJSON . trainingConfig ; } return modelArtifacts ; } } param weightsManifest param path return private loadWeights ( weightsManifest , path ) { const dirName = dirname ( path ) ; const buffers = [ ] ; const weightSpecs = [ ] ; for ( const group of weightsManifest ) { for ( const path of group . paths ) { const weightFilePath = join ( dirName , path ) ; const buffer = fs . readFileSync ( weightFilePath ) ; buffers . push ( buffer ) ; } weightSpecs . push ( ... group . weights ) ; } return [ weightSpecs , toArrayBuffer ( buffers ) ] ; } } param buf return function toArrayBuffer ( buf ) { if ( Array . isArray ( buf ) ) { const newBuf = Buffer . concat ( buf ) ; return newBuf . buffer . slice ( newBuf . byteOffset , newBuf . byteOffset + newBuf . byteLength ) ; } else { return buf . buffer . slice ( buf . byteOffset , buf . byteOffset + buf . byteLength ) ; } }