From 084cad5fd8e21d978b21f21a9d0665cb2a9eda47 Mon Sep 17 00:00:00 2001 From: ppf30 Date: Wed, 17 Dec 2025 19:46:01 +0100 Subject: [PATCH] predict funciona pero no almacena las predicciones en MongoDB --- controllers/predictController.js | 32 +++++++++++++++++++++++++------- model/Prediction.js | 2 +- server.js | 11 +++++------ services/tfModelService.js | 13 ++++++++++--- 4 files changed, 41 insertions(+), 17 deletions(-) diff --git a/controllers/predictController.js b/controllers/predictController.js index 20bc61e3..3da42fbd 100644 --- a/controllers/predictController.js +++ b/controllers/predictController.js @@ -1,5 +1,7 @@ + // controllers/predictController.js const { getModelInfo, predict } = require("../services/tfModelService"); +const Prediction = require("../model/Prediction"); function health(req, res) { res.json({ @@ -60,20 +62,36 @@ async function doPredict(req, res) { }); } - const prediction = await predict(features); + // Ejecutar el modelo + const predictionValue = await predict(features); const latencyMs = Date.now() - start; - const timestamp = new Date().toISOString(); + const timestamp = new Date(); - // De momento sin MongoDB → predictionId null - res.status(201).json({ - predictionId: null, - prediction, + // Guardar en Mongo solo campos válidos + const responsePred = await Prediction.create({ + features, + prediction: predictionValue, timestamp, + latencyMs, + featureCount: meta.featureCount, + scalerVersion: meta.scalerVersion || "v1", + createdAt: timestamp, + predictGroup: "predict" + }); + + res.status(201).json({ + predictionId: responsePred._id, + prediction: predictionValue, + timestamp: timestamp.toISOString(), latencyMs }); + } catch (err) { console.error("Error en /predict:", err); - res.status(500).json({ error: "Internal error" }); + + res.status(500).json({ + error: "Internal error", + }); } } diff --git a/model/Prediction.js b/model/Prediction.js index da618943..c7cbe82c 100644 --- a/model/Prediction.js +++ b/model/Prediction.js @@ -20,4 +20,4 @@ const PredictionSchema = new Schema({ }); -module.exports = mongoose.model('Prediction', PredictionSchema); \ No newline at end of file +module.exports = mongoose.model("Prediction", PredictionSchema); \ No newline at end of file diff --git a/server.js b/server.js index f853a215..5b7adcac 100644 --- a/server.js +++ b/server.js @@ -10,20 +10,19 @@ const predictRoutes = require("./routes/predictRoutes"); const { initModel } = require("./services/tfModelService"); const PORT = process.env.PORT || 3002; - - -app.use(express.json()); - +const MONGO_URI = process.env.MONGO_URI; // conectar a Mongo mongoose - .connect(process.env.MONGO_URI) - .then(() => console.log("MongoDB conectado (PREDICT)")) + .connect(MONGO_URI) + .then(() => {console.log("MongoDB conectado (PREDICT)")}) .catch((err) => { console.error("Error al conectar MongoDB:", err); process.exit(1); }); +app.use(express.json()); + // Servir la carpeta del modelo TFJS (model/model.json + pesos) const modelDir = path.resolve(__dirname, "model"); app.use("/model", express.static(modelDir)); diff --git a/services/tfModelService.js b/services/tfModelService.js index 01af4168..71ec499b 100644 --- a/services/tfModelService.js +++ b/services/tfModelService.js @@ -34,7 +34,10 @@ function wasmFileDirUrl() { return pathToFileURL(distFsPath + path.sep).href; } - +/** + * Inicializa backend WASM y carga el GraphModel + * serverUrl: ej. http://localhost:3002 + */ async function initModel(serverUrl) { const wasmPath = wasmFileDirUrl(); wasmBackend.setWasmPaths(wasmPath); @@ -63,6 +66,7 @@ async function initModel(serverUrl) { throw new Error("No se ha podido detectar inputName/outputName/inputDim"); } + // Warm-up const Xwarm = tf.zeros([1, inputDim], "float32"); let out; if (typeof model.executeAsync === "function") { @@ -79,7 +83,10 @@ async function initModel(serverUrl) { console.log("[TF] Modelo listo."); } - +/** + * Ejecuta el modelo con un vector de features + * Devuelve un escalar >= 0 + */ async function predict(features) { if (!ready || !model) { throw new Error("Model not ready"); @@ -115,4 +122,4 @@ module.exports = { initModel, getModelInfo, predict -}; +}; \ No newline at end of file