Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions controllers/predictController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@

// controllers/predictController.js
const { getModelInfo, predict } = require("../services/tfModelService");
const Prediction = require("../model/Prediction");

function health(req, res) {
res.json({
Expand Down Expand Up @@ -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",
});
}
}

Expand Down
2 changes: 1 addition & 1 deletion model/Prediction.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@ const PredictionSchema = new Schema({

});

module.exports = mongoose.model('Prediction', PredictionSchema);
module.exports = mongoose.model("Prediction", PredictionSchema);
11 changes: 5 additions & 6 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
13 changes: 10 additions & 3 deletions services/tfModelService.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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") {
Expand All @@ -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");
Expand Down Expand Up @@ -115,4 +122,4 @@ module.exports = {
initModel,
getModelInfo,
predict
};
};