Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function parseJSON(json, xThreshold, yThreshold) {
- const text = JSON.parse(json)['textAnnotations'];
- const response = {
- lines: []
- };
- let words = text.slice(1);
- words = words.sort((a, b) => compare(a, b, yThreshold));
- let curLineYCoord = (words[0].boundingPoly.vertices[0].y + words[0].boundingPoly.vertices[2].y) / 2;
- let curXEnd = words[0].boundingPoly.vertices[2].x;
- let curXStart = words[0].boundingPoly.vertices[0].x;
- let line = {
- y: curLineYCoord,
- words: []
- };
- let compledtedWord = words[0].description;
- for (let i = 1; i < words.length; i++) {
- const vertices = words[i].boundingPoly.vertices;
- const curWord = words[i].description;
- const yMid = (vertices[0].y + vertices[2].y) / 2
- const xStart = vertices[0].x;
- if (yMid <= curLineYCoord + yThreshold && yMid >= curLineYCoord - yThreshold) {
- if (xStart <= curXEnd + xThreshold) {
- compledtedWord += curWord;
- curXEnd = vertices[2].x;
- } else {
- line.words.push({
- word: compledtedWord,
- x1: curXStart,
- x2: curXEnd
- });
- curXEnd = vertices[2].x;
- compledtedWord = words[i].description;
- curXStart = vertices[0].x;
- }
- } else {
- line.words.push({
- word: compledtedWord,
- x1: curXStart,
- x2: curXEnd
- });
- response.lines.push(line);
- curLineYCoord = (words[i].boundingPoly.vertices[0].y + words[i].boundingPoly.vertices[2].y) / 2;
- curXStart = vertices[0].x;
- curXEnd = vertices[2].x;
- compledtedWord = words[i].description;
- line = {
- y: curLineYCoord,
- words: []
- };
- }
- }
- console.log(JSON.stringify(response));
- }
- function compare(a, b, yThreshold) {
- const word1Vertices = a.boundingPoly.vertices, word2Vertices = b.boundingPoly.vertices;
- const x1 = word1Vertices[0].x, y1 = word1Vertices[0].y, x2 = word2Vertices[0].x, y2 = word2Vertices[0].y;
- const yMid1 = (y1 + word1Vertices[2].y) / 2, yMid2 = (y2 + word2Vertices[2].y) / 2;
- if (yMid2 <= yMid1 + yThreshold && yMid2 >= yMid1 - yThreshold) {
- if (x1 > x2) {
- return 1;
- } else if (x1 < x2) {
- return -1;
- } else {
- return 0;
- }
- } else if (y1 > y2) {
- return 1;
- } else if (y1 < y2) {
- return -1;
- } else if (x1 > x2) {
- return 1;
- } else if (x1 < x2) {
- return -1;
- } else {
- return 0;
- }
- }
- const fs = require('fs');
- const file = fs.readFileSync('./chandrika_node_(coordinate_wise)_file.txt', 'UTF-8');
- parseJSON(file, 5, 10);
Advertisement
Add Comment
Please, Sign In to add comment