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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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 cv2
  18. import numpy as np
  19. from huggingface_hub import snapshot_download
  20. from api.utils.file_utils import get_project_base_directory
  21. from deepdoc.vision import Recognizer
  22. from deepdoc.vision.operators import nms
  23. class LayoutRecognizer(Recognizer):
  24. labels = [
  25. "_background_",
  26. "Text",
  27. "Title",
  28. "Figure",
  29. "Figure caption",
  30. "Table",
  31. "Table caption",
  32. "Header",
  33. "Footer",
  34. "Reference",
  35. "Equation",
  36. ]
  37. def __init__(self, domain):
  38. try:
  39. model_dir = os.path.join(
  40. get_project_base_directory(),
  41. "rag/res/deepdoc")
  42. super().__init__(self.labels, domain, model_dir)
  43. except Exception:
  44. model_dir = snapshot_download(repo_id="InfiniFlow/deepdoc",
  45. local_dir=os.path.join(get_project_base_directory(), "rag/res/deepdoc"),
  46. local_dir_use_symlinks=False)
  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 if float(b["score"]) >= 0.8 or b["type"] not in self.garbage_layouts]
  74. lts = self.sort_Y_firstly(lts, np.mean(
  75. [lt["bottom"] - lt["top"] for lt 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
  138. class LayoutRecognizer4YOLOv10(LayoutRecognizer):
  139. labels = [
  140. "title",
  141. "Text",
  142. "Reference",
  143. "Figure",
  144. "Figure caption",
  145. "Table",
  146. "Table caption",
  147. "Table caption",
  148. "Equation",
  149. "Figure caption",
  150. ]
  151. def __init__(self, domain):
  152. domain = "layout"
  153. super().__init__(domain)
  154. self.auto = False
  155. self.scaleFill = False
  156. self.scaleup = True
  157. self.stride = 32
  158. self.center = True
  159. def preprocess(self, image_list):
  160. inputs = []
  161. new_shape = self.input_shape # height, width
  162. for img in image_list:
  163. shape = img.shape[:2]# current shape [height, width]
  164. # Scale ratio (new / old)
  165. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  166. # Compute padding
  167. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  168. dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
  169. dw /= 2 # divide padding into 2 sides
  170. dh /= 2
  171. ww, hh = new_unpad
  172. img = np.array(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)).astype(np.float32)
  173. img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
  174. top, bottom = int(round(dh - 0.1)) if self.center else 0, int(round(dh + 0.1))
  175. left, right = int(round(dw - 0.1)) if self.center else 0, int(round(dw + 0.1))
  176. img = cv2.copyMakeBorder(
  177. img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)
  178. ) # add border
  179. img /= 255.0
  180. img = img.transpose(2, 0, 1)
  181. img = img[np.newaxis, :, :, :].astype(np.float32)
  182. inputs.append({self.input_names[0]: img, "scale_factor": [shape[1]/ww, shape[0]/hh, dw, dh]})
  183. return inputs
  184. def postprocess(self, boxes, inputs, thr):
  185. thr = 0.08
  186. boxes = np.squeeze(boxes)
  187. scores = boxes[:, 4]
  188. boxes = boxes[scores > thr, :]
  189. scores = scores[scores > thr]
  190. if len(boxes) == 0:
  191. return []
  192. class_ids = boxes[:, -1].astype(int)
  193. boxes = boxes[:, :4]
  194. boxes[:, 0] -= inputs["scale_factor"][2]
  195. boxes[:, 2] -= inputs["scale_factor"][2]
  196. boxes[:, 1] -= inputs["scale_factor"][3]
  197. boxes[:, 3] -= inputs["scale_factor"][3]
  198. input_shape = np.array([inputs["scale_factor"][0], inputs["scale_factor"][1], inputs["scale_factor"][0],
  199. inputs["scale_factor"][1]])
  200. boxes = np.multiply(boxes, input_shape, dtype=np.float32)
  201. unique_class_ids = np.unique(class_ids)
  202. indices = []
  203. for class_id in unique_class_ids:
  204. class_indices = np.where(class_ids == class_id)[0]
  205. class_boxes = boxes[class_indices, :]
  206. class_scores = scores[class_indices]
  207. class_keep_boxes = nms(class_boxes, class_scores, 0.45)
  208. indices.extend(class_indices[class_keep_boxes])
  209. return [{
  210. "type": self.label_list[class_ids[i]].lower(),
  211. "bbox": [float(t) for t in boxes[i].tolist()],
  212. "score": float(scores[i])
  213. } for i in indices]