* If the underlying model is not loaded, load it. * * @param {() => any} loadingCallback An optional callback function that will * be invoked when the model is being loaded.
(loadingCallback)
| 83 | * be invoked when the model is being loaded. |
| 84 | */ |
| 85 | async ensureModelLoaded(loadingCallback) { |
| 86 | if (this.model == null) { |
| 87 | console.log('Loading image classifier model...'); |
| 88 | if (loadingCallback != null) { |
| 89 | loadingCallback(); |
| 90 | } |
| 91 | |
| 92 | let cachedModelJsonUrl; |
| 93 | if (isNode()) { |
| 94 | // Attempt to find and load model cached on file system if running |
| 95 | // in Node.js. |
| 96 | const fs = require('fs'); |
| 97 | const path = require('path'); |
| 98 | const cachedModelJsonPath = path.join( |
| 99 | this.getFileSystemCacheDirectory_(), 'model.json'); |
| 100 | if (fs.existsSync(cachedModelJsonPath)) { |
| 101 | cachedModelJsonUrl = `file://${cachedModelJsonPath}`; |
| 102 | console.log(`Found cached model at ${cachedModelJsonUrl}`); |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | console.time('Model loading'); |
| 107 | this.model = await tf.loadLayersModel( |
| 108 | cachedModelJsonUrl == null ? |
| 109 | MOBILENET_MODEL_URL : cachedModelJsonUrl); |
| 110 | console.timeEnd('Model loading'); |
| 111 | |
| 112 | if (isNode() && cachedModelJsonUrl == null) { |
| 113 | // Cache model on file system if running in Node.js. |
| 114 | const cacheDir = this.getFileSystemCacheDirectory_(); |
| 115 | try { |
| 116 | await this.model.save(`file://${cacheDir}`); |
| 117 | console.log(`Cached model at ${cacheDir}`); |
| 118 | } catch (err) { |
| 119 | console.warn(`Failed to save model at cache directory: ${cacheDir}`); |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | /** |
| 126 | * Search for images with content matching target wrods. |
no test coverage detected