-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
61 lines (48 loc) · 1.4 KB
/
Copy pathapp.js
File metadata and controls
61 lines (48 loc) · 1.4 KB
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
const express = require('express');
const Tesseract = require('tesseract.js');
const fs = require('fs');
const app = express();
const port = 3000;
const keywords = ['pipe', 'banana', 'apple', 'carrot', 'book', ];
app.get('/', (req, res) => {
const imageBuffer = fs.readFileSync('ocr.png');
Tesseract.recognize(
imageBuffer,
'eng',
{ logger: (info) => console.log(info) }
).then(({ data: { text } }) => {
let closestMatch = '';
let minDistance = Number.MAX_VALUE;
for (const keyword of keywords) {
const distance = levenshteinDistance(text, keyword);
if (distance < minDistance) {
minDistance = distance;
closestMatch = keyword;
}
}
res.send(`Recognized Text: ${text}<br>Closest Match: ${closestMatch}`);
});
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
function levenshteinDistance(s1, s2) {
const m = s1.length;
const n = s2.length;
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
for (let i = 0; i <= m; i++) {
for (let j = 0; j <= n; j++) {
if (i === 0) dp[i][j] = j;
else if (j === 0) dp[i][j] = i;
else {
const cost = s1[i - 1] !== s2[j - 1] ? 1 : 0;
dp[i][j] = Math.min(
dp[i - 1][j - 1] + cost,
dp[i][j - 1] + 1,
dp[i - 1][j] + 1
);
}
}
}
return dp[m][n];
}