Spaces:
Running
Running
Update server.js
Browse files
server.js
CHANGED
@@ -1,6 +1,8 @@
|
|
1 |
'use strict';
|
2 |
|
3 |
import express from 'express';
|
|
|
|
|
4 |
import Lens from 'chrome-lens-ocr';
|
5 |
|
6 |
// Constants
|
@@ -9,16 +11,42 @@ const HOST = '0.0.0.0';
|
|
9 |
|
10 |
// App
|
11 |
const app = express();
|
|
|
|
|
12 |
app.get('/', (req, res) => {
|
13 |
res.send('Hello World from ExpressJS! This example is from the NodeJS Docs: https://nodejs.org/en/docs/guides/nodejs-docker-webapp/');
|
14 |
});
|
15 |
-
const lens = new Lens();
|
16 |
|
17 |
app.get('/scanByUrl', async (req, res) => {
|
18 |
const { url } = req.query;
|
|
|
|
|
|
|
|
|
|
|
19 |
try {
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
const combinedText = data.segments.map(segment => segment.text).join('\n\n');
|
|
|
22 |
res.json({ combinedText, detailedData: data });
|
23 |
} catch (error) {
|
24 |
res.status(500).json({ error: error.message });
|
|
|
1 |
'use strict';
|
2 |
|
3 |
import express from 'express';
|
4 |
+
import fetch from 'node-fetch';
|
5 |
+
import sharp from 'sharp';
|
6 |
import Lens from 'chrome-lens-ocr';
|
7 |
|
8 |
// Constants
|
|
|
11 |
|
12 |
// App
|
13 |
const app = express();
|
14 |
+
const lens = new Lens();
|
15 |
+
|
16 |
app.get('/', (req, res) => {
|
17 |
res.send('Hello World from ExpressJS! This example is from the NodeJS Docs: https://nodejs.org/en/docs/guides/nodejs-docker-webapp/');
|
18 |
});
|
|
|
19 |
|
20 |
app.get('/scanByUrl', async (req, res) => {
|
21 |
const { url } = req.query;
|
22 |
+
|
23 |
+
if (!url) {
|
24 |
+
return res.status(400).json({ error: 'Image URL is required' });
|
25 |
+
}
|
26 |
+
|
27 |
try {
|
28 |
+
// Fetch the image
|
29 |
+
const response = await fetch(url);
|
30 |
+
if (!response.ok) throw new Error('Failed to fetch image');
|
31 |
+
|
32 |
+
const buffer = await response.arrayBuffer();
|
33 |
+
const imageBuffer = Buffer.from(buffer);
|
34 |
+
|
35 |
+
// Get image metadata
|
36 |
+
const metadata = await sharp(imageBuffer).metadata();
|
37 |
+
|
38 |
+
// Resize if necessary
|
39 |
+
let processedImage = imageBuffer;
|
40 |
+
if (metadata.width > 1000 || metadata.height > 1000) {
|
41 |
+
processedImage = await sharp(imageBuffer)
|
42 |
+
.resize(1000, 1000, { fit: 'inside' })
|
43 |
+
.toBuffer();
|
44 |
+
}
|
45 |
+
|
46 |
+
// Scan with Chrome Lens OCR
|
47 |
+
const data = await lens.scanByBuffer(processedImage);
|
48 |
const combinedText = data.segments.map(segment => segment.text).join('\n\n');
|
49 |
+
|
50 |
res.json({ combinedText, detailedData: data });
|
51 |
} catch (error) {
|
52 |
res.status(500).json({ error: error.message });
|