-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathserver_all.js
More file actions
195 lines (157 loc) · 4.93 KB
/
Copy pathserver_all.js
File metadata and controls
195 lines (157 loc) · 4.93 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
// server-predict.js
// Servicio 3: PREDICT
// Cumple el contrato oficial: /health, /ready, /predict
const express = require('express');
const path = require('path');
const { pathToFileURL } = require('url');
const tf = require('@tensorflow/tfjs');
const wasmBackend = require('@tensorflow/tfjs-backend-wasm');
const MODEL_VERSION = "v1.0";
const PORT = process.env.PORT || 3002;
// ---------------------------------------------------------------------
// CONFIG EXPRESS
// ---------------------------------------------------------------------
const app = express();
app.use(express.json());
// ---------------------------------------------------------------------
// LOAD TFJS MODEL
// ---------------------------------------------------------------------
let model = null;
let ready = false;
let inputName = null;
let outputName = null;
let inputDim = null;
const modelDir = path.resolve(__dirname, "model");
app.use('/model', express.static(modelDir));
function wasmFileDirUrl() {
const distFsPath = path.join(
__dirname,
"node_modules",
"@tensorflow",
"tfjs-backend-wasm",
"dist"
);
return pathToFileURL(distFsPath + path.sep).href;
}
async function loadModel(serverUrl) {
await tf.setBackend("wasm");
const wasmPath = wasmFileDirUrl();
wasmBackend.setWasmPaths(wasmPath);
await tf.ready();
console.log("[TF] Backend:", tf.getBackend());
const modelUrl = `${serverUrl}/model/model.json`;
console.log("[TF] Cargando modelo:", modelUrl);
model = await tf.loadGraphModel(modelUrl);
if (model && model.inputs && model.inputs.length > 0) {
inputName = model.inputs[0].name;
inputDim = model.inputs[0].shape[1];
}
if (model && model.outputs && model.outputs.length > 0) {
outputName = model.outputs[0].name;
}
console.log("[TF] inputName:", inputName);
console.log("[TF] outputName:", outputName);
console.log("[TF] inputDim:", inputDim);
// warm-up
const Xwarm = tf.zeros([1, inputDim], "float32");
let out = null;
if (typeof model.executeAsync === "function") {
out = await model.executeAsync({ [inputName]: Xwarm });
} else {
out = model.execute({ [inputName]: Xwarm });
}
if (Array.isArray(out)) out.forEach(t => t.dispose?.());
else if (out && out.dispose) out.dispose();
Xwarm.dispose();
ready = true;
console.log("[TF] Modelo listo.");
}
// ---------------------------------------------------------------------
// ENDPOINTS
// ---------------------------------------------------------------------
// GET /health
app.get('/health', (req, res) => {
res.json({
status: "ok",
service: "predict"
});
});
// GET /ready
app.get('/ready', (req, res) => {
if (!ready) {
return res.status(503).json({
ready: false,
modelVersion: MODEL_VERSION,
message: "Model is still loading"
});
}
res.json({
ready: true,
modelVersion: MODEL_VERSION
});
});
// POST /predict
app.post('/predict', async (req, res) => {
const start = Date.now();
try {
if (!ready || !model) {
return res.status(503).json({
error: "Model not ready",
ready: false
});
}
const { features, meta } = req.body;
// Validaciones contrato
if (!features) {
return res.status(400).json({ error: "Missing features" });
}
if (!meta || typeof meta !== "object") {
return res.status(400).json({ error: "Missing meta object" });
}
const { featureCount, dataId, source, correlationId } = meta;
if (featureCount !== inputDim) {
return res.status(400).json({
error: `featureCount must be ${inputDim}, received ${featureCount}`
});
}
if (!Array.isArray(features) || features.length !== inputDim) {
return res.status(400).json({
error: `features must be an array of ${inputDim} numbers`
});
}
// Tensores
const X = tf.tensor2d([features], [1, inputDim], "float32");
let out;
if (typeof model.executeAsync === "function") {
out = await model.executeAsync({ [inputName]: X });
} else {
out = model.execute({ [inputName]: X });
}
const preds2d = Array.isArray(out)
? await out[0].array()
: await out.array();
const prediction_real = preds2d[0][0];
const prediction = Math.max(prediction_real, 0);
// Limpieza
if (Array.isArray(out)) out.forEach(t => t.dispose?.());
else if (out.dispose) out.dispose();
X.dispose();
const latencyMs = Date.now() - start;
// Respuesta 201
res.status(201).json({
prediction,
latencyMs
});
} catch (err) {
console.error("Error en /predict:", err);
res.status(500).json({ error: "Internal error" });
}
});
// ---------------------------------------------------------------------
// START SERVER
// ---------------------------------------------------------------------
app.listen(PORT, async () => {
const serverUrl = `http://localhost:${PORT}`;
console.log(`[PREDICT] Servicio en ${serverUrl}`);
await loadModel(serverUrl);
});