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.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  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. model_dir = snapshot_download(repo_id="InfiniFlow/deepdoc")
  38. super().__init__(self.labels, domain, model_dir)#os.path.join(get_project_base_directory(), "rag/res/deepdoc/"))
  39. self.garbage_layouts = ["footer", "header", "reference"]
  40. def __call__(self, image_list, ocr_res, scale_factor=3, thr=0.2, batch_size=16, drop=True):
  41. def __is_garbage(b):
  42. patt = [r"^•+$", r"(版权归©|免责条款|地址[::])", r"\.{3,}", "^[0-9]{1,2} / ?[0-9]{1,2}$",
  43. r"^[0-9]{1,2} of [0-9]{1,2}$", "^http://[^ ]{12,}",
  44. "(资料|数据)来源[::]", "[0-9a-z._-]+@[a-z0-9-]+\\.[a-z]{2,3}",
  45. "\\(cid *: *[0-9]+ *\\)"
  46. ]
  47. return any([re.search(p, b["text"]) for p in patt])
  48. layouts = super().__call__(image_list, thr, batch_size)
  49. # save_results(image_list, layouts, self.labels, output_dir='output/', threshold=0.7)
  50. assert len(image_list) == len(ocr_res)
  51. # Tag layout type
  52. boxes = []
  53. assert len(image_list) == len(layouts)
  54. garbages = {}
  55. page_layout = []
  56. for pn, lts in enumerate(layouts):
  57. bxs = ocr_res[pn]
  58. lts = [{"type": b["type"],
  59. "score": float(b["score"]),
  60. "x0": b["bbox"][0] / scale_factor, "x1": b["bbox"][2] / scale_factor,
  61. "top": b["bbox"][1] / scale_factor, "bottom": b["bbox"][-1] / scale_factor,
  62. "page_number": pn,
  63. } for b in lts]
  64. lts = self.sort_Y_firstly(lts, np.mean([l["bottom"]-l["top"] for l in lts]) / 2)
  65. lts = self.layouts_cleanup(bxs, lts)
  66. page_layout.append(lts)
  67. # Tag layout type, layouts are ready
  68. def findLayout(ty):
  69. nonlocal bxs, lts, self
  70. lts_ = [lt for lt in lts if lt["type"] == ty]
  71. i = 0
  72. while i < len(bxs):
  73. if bxs[i].get("layout_type"):
  74. i += 1
  75. continue
  76. if __is_garbage(bxs[i]):
  77. bxs.pop(i)
  78. continue
  79. ii = self.find_overlapped_with_threashold(bxs[i], lts_,
  80. thr=0.4)
  81. if ii is None: # belong to nothing
  82. bxs[i]["layout_type"] = ""
  83. i += 1
  84. continue
  85. lts_[ii]["visited"] = True
  86. keep_feats = [
  87. lts_[ii]["type"] == "footer" and bxs[i]["bottom"] < image_list[pn].size[1]*0.9/scale_factor,
  88. lts_[ii]["type"] == "header" and bxs[i]["top"] > image_list[pn].size[1]*0.1/scale_factor,
  89. ]
  90. if drop and lts_[ii]["type"] in self.garbage_layouts and not any(keep_feats):
  91. if lts_[ii]["type"] not in garbages:
  92. garbages[lts_[ii]["type"]] = []
  93. garbages[lts_[ii]["type"]].append(bxs[i]["text"])
  94. bxs.pop(i)
  95. continue
  96. bxs[i]["layoutno"] = f"{ty}-{ii}"
  97. bxs[i]["layout_type"] = lts_[ii]["type"] if lts_[ii]["type"]!="equation" else "figure"
  98. i += 1
  99. for lt in ["footer", "header", "reference", "figure caption",
  100. "table caption", "title", "table", "text", "figure", "equation"]:
  101. findLayout(lt)
  102. # add box to figure layouts which has not text box
  103. for i, lt in enumerate(
  104. [lt for lt in lts if lt["type"] in ["figure","equation"]]):
  105. if lt.get("visited"):
  106. continue
  107. lt = deepcopy(lt)
  108. del lt["type"]
  109. lt["text"] = ""
  110. lt["layout_type"] = "figure"
  111. lt["layoutno"] = f"figure-{i}"
  112. bxs.append(lt)
  113. boxes.extend(bxs)
  114. ocr_res = boxes
  115. garbag_set = set()
  116. for k in garbages.keys():
  117. garbages[k] = Counter(garbages[k])
  118. for g, c in garbages[k].items():
  119. if c > 1:
  120. garbag_set.add(g)
  121. ocr_res = [b for b in ocr_res if b["text"].strip() not in garbag_set]
  122. return ocr_res, page_layout