-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
77 lines (66 loc) · 2.36 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
const express = require('express');
const csv = require('csv-parser');
const fs = require('fs');
const multer = require('multer');
const { createWorker } = require('tesseract.js');
const app = express();
// Middleware to parse JSON
app.use(express.json());
// Setup multer for handling file uploads
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
// Endpoint to handle ingredient lookup
app.get('/ingredients/:name', (req, res) => {
const ingredientName = req.params.name;
const results = [];
fs.createReadStream('ingredients.csv')
.pipe(csv())
.on('data', (data) => {
if (data.name === ingredientName) {
results.push({
source: data.source,
nature: data.nature
});
}
})
.on('end', () => {
if (results.length > 0) {
res.json(results);
} else {
res.status(404).json({ message: 'Ingredient not found' });
}
});
});
// Endpoint to handle image OCR and ingredient lookup
app.post('/scan', upload.single('image'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ message: 'No image uploaded' });
}
// Perform OCR on the uploaded image
const worker = createWorker();
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
const { data: { text } } = await worker.recognize(req.file.buffer);
await worker.terminate();
// Extract ingredient names from OCR text
const ingredients = text.split('\n').filter(ingredient => ingredient.trim() !== '');
// Lookup details of each ingredient
const ingredientDetails = [];
for (const ingredient of ingredients) {
const response = await fetch(`http://localhost:3000/ingredients/${ingredient}`);
const data = await response.json();
ingredientDetails.push(...data);
}
// Respond with ingredient details
res.json(ingredientDetails);
} catch (error) {
console.error(error);
res.status(500).json({ message: 'Internal server error' });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});