-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtextRecognition.js
85 lines (67 loc) · 2.6 KB
/
textRecognition.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
78
79
80
81
82
83
84
85
const vision = require("@google-cloud/vision");
const files = require("fs");
const crypto = require('crypto');
const sizeOf = require('image-size')
class TextRecognition {
constructor() {
this.client = new vision.ImageAnnotatorClient();
}
/**
* Accepts a base64 encoded image and uses the Google Vision API to perform
* text recognition
* @param {string} image64 The base64 encoded image
* @returns The text and bounding boxes extracted from the input image
*/
async getTextData(image64) {
const fileName = __dirname + "/image_cache/" + crypto.randomUUID() + ".png";
files.writeFileSync(fileName, image64, 'base64', (err) => {
if (err) {
console.log(err);
return null;
}
});
const imageSize = sizeOf(fileName);
let imageWidth = imageSize.width;
let imageHeight = imageSize.height;
// Request for text recognition to be performed on the given image
const [result] = await this.client.documentTextDetection(fileName);
const fullText = result.fullTextAnnotation;
// Get rid of the temporary image
files.rmSync(fileName);
if (!fullText) {
console.log("No text detected");
return null;
}
const getWordString = (word) => {
let sentence = "";
word.symbols.forEach(symbol => {
sentence += symbol.text;
let symbolBreak = symbol.property?.detectedBreak;
if (symbolBreak && symbolBreak.type === "SPACE")
sentence += " ";
});
return sentence;
}
const normalizeVertices = (vertices) => {
return vertices.map(vertex => {
return { x: vertex.x / imageWidth, y: vertex.y / imageHeight }
});
}
let textAndBounds = [];
fullText.pages.forEach(page => {
page.blocks.forEach(block => {
block.paragraphs.forEach(paragraph => {
let sentence = "";
paragraph.words.forEach(word => {
sentence += getWordString(word);
})
let vertices = normalizeVertices(paragraph.boundingBox.vertices);
let selectedVertices = [vertices[0], vertices[2]]; // Only want top left and bottom-right
textAndBounds.push({text: sentence, boundingBox: selectedVertices })
})
})
})
return textAndBounds;
}
}
module.exports = TextRecognition;