geetanjali123

NodeCode

Mar 3rd, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.88 KB | None | 0 0
  1. function parseJSON(json, xThreshold, yThreshold) {
  2. const text = JSON.parse(json)['textAnnotations'];
  3. const response = {
  4. lines: []
  5. };
  6. let words = text.slice(1);
  7. words = words.sort((a, b) => compare(a, b, yThreshold));
  8. let curLineYCoord = (words[0].boundingPoly.vertices[0].y + words[0].boundingPoly.vertices[2].y) / 2;
  9. let curXEnd = words[0].boundingPoly.vertices[2].x;
  10. let curXStart = words[0].boundingPoly.vertices[0].x;
  11. let line = {
  12. y: curLineYCoord,
  13. words: []
  14. };
  15. let compledtedWord = words[0].description;
  16. for (let i = 1; i < words.length; i++) {
  17. const vertices = words[i].boundingPoly.vertices;
  18. const curWord = words[i].description;
  19. const yMid = (vertices[0].y + vertices[2].y) / 2
  20. const xStart = vertices[0].x;
  21. if (yMid <= curLineYCoord + yThreshold && yMid >= curLineYCoord - yThreshold) {
  22. if (xStart <= curXEnd + xThreshold) {
  23. compledtedWord += curWord;
  24. curXEnd = vertices[2].x;
  25. } else {
  26. line.words.push({
  27. word: compledtedWord,
  28. x1: curXStart,
  29. x2: curXEnd
  30. });
  31. curXEnd = vertices[2].x;
  32. compledtedWord = words[i].description;
  33. curXStart = vertices[0].x;
  34. }
  35. } else {
  36. line.words.push({
  37. word: compledtedWord,
  38. x1: curXStart,
  39. x2: curXEnd
  40. });
  41. response.lines.push(line);
  42. curLineYCoord = (words[i].boundingPoly.vertices[0].y + words[i].boundingPoly.vertices[2].y) / 2;
  43. curXStart = vertices[0].x;
  44. curXEnd = vertices[2].x;
  45. compledtedWord = words[i].description;
  46. line = {
  47. y: curLineYCoord,
  48. words: []
  49. };
  50. }
  51. }
  52. console.log(JSON.stringify(response));
  53. }
  54.  
  55. function compare(a, b, yThreshold) {
  56. const word1Vertices = a.boundingPoly.vertices, word2Vertices = b.boundingPoly.vertices;
  57. const x1 = word1Vertices[0].x, y1 = word1Vertices[0].y, x2 = word2Vertices[0].x, y2 = word2Vertices[0].y;
  58. const yMid1 = (y1 + word1Vertices[2].y) / 2, yMid2 = (y2 + word2Vertices[2].y) / 2;
  59. if (yMid2 <= yMid1 + yThreshold && yMid2 >= yMid1 - yThreshold) {
  60. if (x1 > x2) {
  61. return 1;
  62. } else if (x1 < x2) {
  63. return -1;
  64. } else {
  65. return 0;
  66. }
  67. } else if (y1 > y2) {
  68. return 1;
  69. } else if (y1 < y2) {
  70. return -1;
  71. } else if (x1 > x2) {
  72. return 1;
  73. } else if (x1 < x2) {
  74. return -1;
  75. } else {
  76. return 0;
  77. }
  78. }
  79.  
  80. const fs = require('fs');
  81. const file = fs.readFileSync('./chandrika_node_(coordinate_wise)_file.txt', 'UTF-8');
  82. parseJSON(file, 5, 10);
Advertisement
Add Comment
Please, Sign In to add comment