def predictImage(img_path): # load model model = load_model("model.h5") # load a single image new_image = load_image(img_path) # check prediction pred = model.predict(new_image) return str(pred)
/** remove warning that you don't care about */
function cleanWarning(error) {
return error.replace(/Detector is not able to detect the language reliably.\n/g,"");
}
function callPython(scriptName, args) {
return new Promise(function(success, reject) {
const script = pythonDir + scriptName;
const pyArgs = [script, JSON.stringify(args) ]
const pyprog = spawn(python, pyArgs );
let result = "";
let resultError = "";
pyprog.stdout.on('data', function(data) {
result += data.toString();
});
pyprog.stderr.on('data', (data) => {
resultError += cleanWarning(data.toString());
});
pyprog.stdout.on("end", function(){
if(resultError == "") {
success(JSON.parse(result));
}else{
console.error(`Python error, you can reproduce the error with: \n${python} ${script} ${pyArgs.join(" ")}`);
const error = new Error(resultError);
console.error(error);
reject(resultError);
}
})
});
}
module.exports.callPython = callPython;
call:const pythonCaller = require("../core/pythonCaller");
const result = await pythonCaller.callPython("preprocessorSentiment.py", {"thekeyYouwant": value});
python:
try:
argu = json.loads(sys.argv[1])
except:
raise Exception("error while loading argument")
const spawn = require("child_process").spawn; const pythonProcess = spawn('python',["path/to/script.py", arg1, arg2, ...]);
import sys
in your python script, and then you can access arg1
using sys.argv[1]
, arg2
using sys.argv[2]
, and so on.print(dataToSendBack) sys.stdout.flush()
pythonProcess.stdout.on('data', (data) => { // Do something with the data returned from python script });
You can put this function in separated file; let's called it 'test.py' for example.
In the Js file:
const { exec } = require('child_process');
function runPythonScript(){
return new Promise((resolve, reject) => {
exec('python test.py', (err, stdout, stderr) => {
if(err) reject(err);
resolve(stdout);
});
});
}
and call the function runPythonScript in express route.
runPythonScript()
.then(result => res.send(result))