//get folders of images to use as classes const glob = require('glob'); const library = require('image-classifier'); const fs = require('fs'); // const const path = require('path') const cliProgress = require('cli-progress'); const multer = require('multer'); const express = require('express'); const app = express(); const upload = multer({ dest: './temp', }) app.post('/classify', upload.single("file"), (req, res) => { const tempPath = req.file.path; console.log(tempPath); classifier.predict(tempPath).then(async (result) => { await fs.unlink(tempPath) res.status(200).json(result); }) // res.status(200).json({message: 'Success'}) }) app.listen(2666); var shouldRebuildModel = false; process.argv.forEach((val, index, array) => { console.log(val) if(val === '--rebuild'){ shouldRebuildModel = true; } }) function getClass(file) { return path.dirname(file).split('/').pop(); } function pGlob(pattern) { return new Promise((resolve, reject) => { glob(pattern, (error, matches) => { if(error) return reject(error); resolve(matches); }) }) } var classifier; async function runAsync() { if(shouldRebuildModel) { classifier = await library.create(); const matches = await pGlob('training images/**/*'); console.log(`Building model with ${matches.length} training items...`) const rebuildBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_grey); rebuildBar.start(matches.length); await Promise.all(matches.map(file => { if(fs.lstatSync(file).isDirectory()) { rebuildBar.increment(); return Promise.resolve(); } const classA = getClass(file); return classifier.addExample(classA, file).then(() => rebuildBar.increment()) })).catch(error => { console.error(error); }); rebuildBar.stop(); console.log('all examples loaded...'); console.log('saving dataset...') await classifier.save('./export.json'); } else { classifier = await library.load('./export.json'); } // const matches = await pGlob('test images/**/*'); // const classifyBar = new cliProgress.SingleBar({}, cliProgress.Presets.shades_grey); // classifyBar.start(matches.length); // await Promise.all(matches.map(async file => { // const baseFileName = path.parse(file).name; // const extension = path.extname(file); // const newClass= await classifier.predict(file); // // console.log(newClass); // return new Promise((resolve, reject) => { // if(!fs.existsSync(path.resolve('sorted images', newClass.label))){ // fs.mkdirSync(path.resolve('sorted images', newClass.label)); // } // fs.copyFile(file, path.resolve('sorted images', newClass.label, `${baseFileName}.${extension}`), () => { // classifyBar.increment(); // resolve() // }); // }) // })) // classifyBar.stop(); } runAsync();