Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

layout_recognizer.py 6.1KB

1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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 huggingface_hub import snapshot_download
  19. from api.db import ParserType
  20. from api.utils.file_utils import get_project_base_directory
  21. from deepdoc.vision import Recognizer
  22. class LayoutRecognizer(Recognizer):
  23. labels = [
  24. "_background_",
  25. "Text",
  26. "Title",
  27. "Figure",
  28. "Figure caption",
  29. "Table",
  30. "Table caption",
  31. "Header",
  32. "Footer",
  33. "Reference",
  34. "Equation",
  35. ]
  36. def __init__(self, domain):
  37. try:
  38. model_dir = snapshot_download(
  39. repo_id="InfiniFlow/deepdoc",
  40. local_dir=os.path.join(
  41. get_project_base_directory(),
  42. "rag/res/deepdoc"),
  43. local_files_only=True)
  44. except Exception as e:
  45. model_dir = snapshot_download(repo_id="InfiniFlow/deepdoc")
  46. # os.path.join(get_project_base_directory(), "rag/res/deepdoc/"))
  47. super().__init__(self.labels, domain, model_dir)
  48. self.garbage_layouts = ["footer", "header", "reference"]
  49. def __call__(self, image_list, ocr_res, scale_factor=3,
  50. thr=0.2, batch_size=16, drop=True):
  51. def __is_garbage(b):
  52. patt = [r"^•+$", r"(版权归©|免责条款|地址[::])", r"\.{3,}", "^[0-9]{1,2} / ?[0-9]{1,2}$",
  53. r"^[0-9]{1,2} of [0-9]{1,2}$", "^http://[^ ]{12,}",
  54. "(资料|数据)来源[::]", "[0-9a-z._-]+@[a-z0-9-]+\\.[a-z]{2,3}",
  55. "\\(cid *: *[0-9]+ *\\)"
  56. ]
  57. return any([re.search(p, b["text"]) for p in patt])
  58. layouts = super().__call__(image_list, thr, batch_size)
  59. # save_results(image_list, layouts, self.labels, output_dir='output/', threshold=0.7)
  60. assert len(image_list) == len(ocr_res)
  61. # Tag layout type
  62. boxes = []
  63. assert len(image_list) == len(layouts)
  64. garbages = {}
  65. page_layout = []
  66. for pn, lts in enumerate(layouts):
  67. bxs = ocr_res[pn]
  68. lts = [{"type": b["type"],
  69. "score": float(b["score"]),
  70. "x0": b["bbox"][0] / scale_factor, "x1": b["bbox"][2] / scale_factor,
  71. "top": b["bbox"][1] / scale_factor, "bottom": b["bbox"][-1] / scale_factor,
  72. "page_number": pn,
  73. } for b in lts]
  74. lts = self.sort_Y_firstly(lts, np.mean(
  75. [l["bottom"] - l["top"] for l in lts]) / 2)
  76. lts = self.layouts_cleanup(bxs, lts)
  77. page_layout.append(lts)
  78. # Tag layout type, layouts are ready
  79. def findLayout(ty):
  80. nonlocal bxs, lts, self
  81. lts_ = [lt for lt in lts if lt["type"] == ty]
  82. i = 0
  83. while i < len(bxs):
  84. if bxs[i].get("layout_type"):
  85. i += 1
  86. continue
  87. if __is_garbage(bxs[i]):
  88. bxs.pop(i)
  89. continue
  90. ii = self.find_overlapped_with_threashold(bxs[i], lts_,
  91. thr=0.4)
  92. if ii is None: # belong to nothing
  93. bxs[i]["layout_type"] = ""
  94. i += 1
  95. continue
  96. lts_[ii]["visited"] = True
  97. keep_feats = [
  98. lts_[
  99. ii]["type"] == "footer" and bxs[i]["bottom"] < image_list[pn].size[1] * 0.9 / scale_factor,
  100. lts_[
  101. ii]["type"] == "header" and bxs[i]["top"] > image_list[pn].size[1] * 0.1 / scale_factor,
  102. ]
  103. if drop and lts_[
  104. ii]["type"] in self.garbage_layouts and not any(keep_feats):
  105. if lts_[ii]["type"] not in garbages:
  106. garbages[lts_[ii]["type"]] = []
  107. garbages[lts_[ii]["type"]].append(bxs[i]["text"])
  108. bxs.pop(i)
  109. continue
  110. bxs[i]["layoutno"] = f"{ty}-{ii}"
  111. bxs[i]["layout_type"] = lts_[ii]["type"] if lts_[
  112. ii]["type"] != "equation" else "figure"
  113. i += 1
  114. for lt in ["footer", "header", "reference", "figure caption",
  115. "table caption", "title", "table", "text", "figure", "equation"]:
  116. findLayout(lt)
  117. # add box to figure layouts which has not text box
  118. for i, lt in enumerate(
  119. [lt for lt in lts if lt["type"] in ["figure", "equation"]]):
  120. if lt.get("visited"):
  121. continue
  122. lt = deepcopy(lt)
  123. del lt["type"]
  124. lt["text"] = ""
  125. lt["layout_type"] = "figure"
  126. lt["layoutno"] = f"figure-{i}"
  127. bxs.append(lt)
  128. boxes.extend(bxs)
  129. ocr_res = boxes
  130. garbag_set = set()
  131. for k in garbages.keys():
  132. garbages[k] = Counter(garbages[k])
  133. for g, c in garbages[k].items():
  134. if c > 1:
  135. garbag_set.add(g)
  136. ocr_res = [b for b in ocr_res if b["text"].strip() not in garbag_set]
  137. return ocr_res, page_layout