You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

layout_recognizer.py 5.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # Licensed under the Apache License, Version 2.0 (the "License");
  2. # you may not use this file except in compliance with the License.
  3. # You may obtain a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. #
  13. import os
  14. import re
  15. from collections import Counter
  16. from copy import deepcopy
  17. import numpy as np
  18. from api.utils.file_utils import get_project_base_directory
  19. from deepdoc.vision import Recognizer
  20. class LayoutRecognizer(Recognizer):
  21. labels = [
  22. "_background_",
  23. "Text",
  24. "Title",
  25. "Figure",
  26. "Figure caption",
  27. "Table",
  28. "Table caption",
  29. "Header",
  30. "Footer",
  31. "Reference",
  32. "Equation",
  33. ]
  34. def __init__(self, domain):
  35. super().__init__(self.labels, domain,
  36. os.path.join(get_project_base_directory(), "rag/res/deepdoc/"))
  37. def __call__(self, image_list, ocr_res, scale_factor=3, thr=0.7, batch_size=16):
  38. def __is_garbage(b):
  39. patt = [r"^•+$", r"(版权归©|免责条款|地址[::])", r"\.{3,}", "^[0-9]{1,2} / ?[0-9]{1,2}$",
  40. r"^[0-9]{1,2} of [0-9]{1,2}$", "^http://[^ ]{12,}",
  41. "(资料|数据)来源[::]", "[0-9a-z._-]+@[a-z0-9-]+\\.[a-z]{2,3}",
  42. "\\(cid *: *[0-9]+ *\\)"
  43. ]
  44. return any([re.search(p, b["text"]) for p in patt])
  45. layouts = super().__call__(image_list, thr, batch_size)
  46. # save_results(image_list, layouts, self.labels, output_dir='output/', threshold=0.7)
  47. assert len(image_list) == len(ocr_res)
  48. # Tag layout type
  49. boxes = []
  50. assert len(image_list) == len(layouts)
  51. garbages = {}
  52. page_layout = []
  53. for pn, lts in enumerate(layouts):
  54. bxs = ocr_res[pn]
  55. lts = [{"type": b["type"],
  56. "score": float(b["score"]),
  57. "x0": b["bbox"][0] / scale_factor, "x1": b["bbox"][2] / scale_factor,
  58. "top": b["bbox"][1] / scale_factor, "bottom": b["bbox"][-1] / scale_factor,
  59. "page_number": pn,
  60. } for b in lts]
  61. lts = self.sort_Y_firstly(lts, np.mean([l["bottom"]-l["top"] for l in lts]) / 2)
  62. lts = self.layouts_cleanup(bxs, lts)
  63. page_layout.append(lts)
  64. # Tag layout type, layouts are ready
  65. def findLayout(ty):
  66. nonlocal bxs, lts, self
  67. lts_ = [lt for lt in lts if lt["type"] == ty]
  68. i = 0
  69. while i < len(bxs):
  70. if bxs[i].get("layout_type"):
  71. i += 1
  72. continue
  73. if __is_garbage(bxs[i]):
  74. bxs.pop(i)
  75. continue
  76. ii = self.find_overlapped_with_threashold(bxs[i], lts_,
  77. thr=0.4)
  78. if ii is None: # belong to nothing
  79. bxs[i]["layout_type"] = ""
  80. i += 1
  81. continue
  82. lts_[ii]["visited"] = True
  83. if lts_[ii]["type"] in ["footer", "header", "reference"]:
  84. if lts_[ii]["type"] not in garbages:
  85. garbages[lts_[ii]["type"]] = []
  86. garbages[lts_[ii]["type"]].append(bxs[i]["text"])
  87. bxs.pop(i)
  88. continue
  89. bxs[i]["layoutno"] = f"{ty}-{ii}"
  90. bxs[i]["layout_type"] = lts_[ii]["type"]
  91. i += 1
  92. for lt in ["footer", "header", "reference", "figure caption",
  93. "table caption", "title", "text", "table", "figure", "equation"]:
  94. findLayout(lt)
  95. # add box to figure layouts which has not text box
  96. for i, lt in enumerate(
  97. [lt for lt in lts if lt["type"] == "figure"]):
  98. if lt.get("visited"):
  99. continue
  100. lt = deepcopy(lt)
  101. del lt["type"]
  102. lt["text"] = ""
  103. lt["layout_type"] = "figure"
  104. lt["layoutno"] = f"figure-{i}"
  105. bxs.append(lt)
  106. boxes.extend(bxs)
  107. ocr_res = boxes
  108. garbag_set = set()
  109. for k in garbages.keys():
  110. garbages[k] = Counter(garbages[k])
  111. for g, c in garbages[k].items():
  112. if c > 1:
  113. garbag_set.add(g)
  114. ocr_res = [b for b in ocr_res if b["text"].strip() not in garbag_set]
  115. return ocr_res, page_layout