Skip to content

Instantly share code, notes, and snippets.

@goodwin64
Created March 22, 2024 21:14
Show Gist options
  • Save goodwin64/7613f26b87140f4462f9fae9eacb7afb to your computer and use it in GitHub Desktop.
Save goodwin64/7613f26b87140f4462f9fae9eacb7afb to your computer and use it in GitHub Desktop.
import path from 'path';
import express from 'express';
import fileUpload from 'express-fileupload';
import { pythonRunningProcess, spawnPythonProcess } from './spawn-python-process';
import { useRunningPythonServer } from './use-running-python-server';
const downloadsFolder = path.resolve(__dirname, './downloads');
let isProcessing = false;
const requestQueue: Array<{
filePath: string;
res: any; // Express response
}> = [];
async function processQueue() {
if (requestQueue.length === 0) {
isProcessing = false;
return;
}
isProcessing = true;
const firstEntry = requestQueue.shift();
if (!firstEntry) {
return;
}
const { filePath, res } = firstEntry;
try {
const solution = await useRunningPythonServer(filePath);
console.log('solution: ', solution);
res.status(200).send(solution);
processQueue();
} catch (error) {
res.status(500).send(error);
console.error(error);
processQueue();
}
}
async function handleFileUpload(req, res) {
try {
if (!pythonRunningProcess) {
return res.status(500).send('python process is not running');
}
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded');
}
if (Object.keys(req.files).length > 1) {
return res.status(400).send('Provide a single file');
}
const imageFile = req.files.imageFile;
const fileName = `image-${Date.now()}.png`;
const filePath = path.join(downloadsFolder, fileName);
console.log('filePath: ', filePath);
// Use the mv() method to place the file somewhere on your server
imageFile.mv(filePath, async function (err) {
if (err) {
return res.status(500).send(err);
}
requestQueue.push({ filePath, res });
if (isProcessing) {
return;
}
processQueue();
});
} catch (err) {
console.error(err);
return res.status(500).send(err);
}
}
export function runNodeListenerServer() {
const app = express();
app.use(
fileUpload({
limits: { fileSize: 20 * 1024 }, // 20 kb
})
);
console.log('>>> runNodeListenerServer');
const PORT = 3456;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});
// spawn python process only once simultaneously with the server;
// reuse it multiple times later
spawnPythonProcess();
app.get('/recognise-image', (req, res) => res.status(200).send('python process is running'));
app.post('/recognise-image', handleFileUpload);
}
runNodeListenerServer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment