Spaces:
Runtime error
Runtime error
const express = require("express"); | |
const cors = require("cors"); | |
const bodyParser = require("body-parser"); | |
const { spawn } = require("child_process"); | |
const path = require("path"); | |
const app = express(); | |
const PORT = 5000; | |
// Middleware | |
app.use(cors()); | |
app.use(bodyParser.json()); | |
// API Endpoint to run Python script for prediction | |
app.post("/predict", (req, res) => { | |
const text = req.body.text; | |
console.log(`Received text: ${text}`); | |
// Ensure correct Python script path | |
const pythonScriptPath = path.join(__dirname, "run_model.py"); | |
// Spawn Python process to run the model | |
const pythonProcess = spawn("python", [pythonScriptPath, text], { shell: true }); | |
let result = ""; | |
let errorData = ""; | |
// Collect data from stdout (result of prediction) | |
pythonProcess.stdout.on("data", (data) => { | |
result += data.toString(); | |
}); | |
// Collect data from stderr (errors if any) | |
pythonProcess.stderr.on("data", (data) => { | |
errorData += data.toString(); | |
console.error(`Error: ${data}`); | |
}); | |
// When the Python process finishes | |
pythonProcess.on("close", (code) => { | |
console.log(`Python process exited with code ${code}`); | |
if (code === 0) { | |
res.json({ prediction: result.trim() }); | |
} else { | |
res.status(500).json({ error: "Error processing request", details: errorData.trim() }); | |
} | |
}); | |
}); | |
// Start server | |
app.listen(PORT, () => { | |
console.log(`Server is running on port ${PORT}`); | |
}); | |