File size: 1,544 Bytes
efead7f
 
faa2752
4ff3af0
 
804d780
efead7f
 
 
 
 
 
 
4ff3af0
 
efead7f
 
 
804d780
 
 
4ff3af0
 
 
 
 
804d780
4ff3af0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97458da
4ff3af0
804d780
 
 
 
 
 
efead7f
 
97458da
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
'use strict';

import express from 'express';
import fetch from 'node-fetch';
import sharp from 'sharp';
import Lens from 'chrome-lens-ocr';

// Constants
const PORT = 7860;
const HOST = '0.0.0.0';

// App
const app = express();
const lens = new Lens();

app.get('/', (req, res) => {
  res.send('Hello World from ExpressJS! This example is from the NodeJS Docs: https://nodejs.org/en/docs/guides/nodejs-docker-webapp/');
});

app.get('/scanByUrl', async (req, res) => {
  const { url } = req.query;

  if (!url) {
    return res.status(400).json({ error: 'Image URL is required' });
  }

  try {
    // Fetch the image
    const response = await fetch(url);
    if (!response.ok) throw new Error('Failed to fetch image');

    const buffer = await response.arrayBuffer();
    const imageBuffer = Buffer.from(buffer);

    // Get image metadata
    const metadata = await sharp(imageBuffer).metadata();

    // Resize if necessary
    let processedImage = imageBuffer;
    if (metadata.width > 1000 || metadata.height > 1000) {
      processedImage = await sharp(imageBuffer)
        .resize(1000, 1000, { fit: 'inside' })
        .toBuffer();
    }

    // Scan with Chrome Lens OCR
    const data = await lens.scanByBuffer(processedImage);
    const combinedText = data.segments.map(segment => segment.text).join('\n\n');

    res.json({ combinedText, detailedData: data });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(PORT, HOST, () => {
  console.log(`Running on http://${HOST}:${PORT}`);
});