-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
62 lines (48 loc) · 1.48 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const tar = require('tar')
const iltorb = require('iltorb')
const fs = require('fs')
const { TFJS_PATH, TAR_PATH } = require('./constants')
// this hack is required to avoid webpack/rollup/... bundling the required path
const requireFunc =
typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
function isLambda() {
// check for `now dev` environment first
// because `now dev` sets AWS_LAMBDA_FUNCTION_NAME
if (process.env.NOW_REGION === 'dev1') return false
return Boolean(process.env.AWS_LAMBDA_FUNCTION_NAME)
}
async function requireTf() {
const tf = requireFunc(TFJS_PATH)
tf.disableDeprecationWarnings()
return tf
}
async function createTfPromise() {
// if not in lambda environment, just require the actual package
// this is useful as a way to bypass tensorflow-lambda in development
if (!isLambda()) {
return requireFunc('@tensorflow/tfjs-node')
}
// if tfjs-node already exists, just require it
if (fs.existsSync(TFJS_PATH)) {
return requireTf()
}
// else, create the folder and deflate tfjs-node
fs.mkdirSync(TFJS_PATH)
// unzip tfjs-node
await new Promise((resolve, reject) => {
const x = tar.x({ cwd: TFJS_PATH })
x.on('finish', resolve)
x.on('error', reject)
fs.createReadStream(TAR_PATH)
.pipe(iltorb.decompressStream())
.pipe(x)
})
return requireTf()
}
let tfPromise
module.exports = function loadTf() {
if (!tfPromise) {
tfPromise = createTfPromise()
}
return tfPromise
}