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

layout_recognizer.py 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import os
  17. import re
  18. from collections import Counter
  19. from copy import deepcopy
  20. import cv2
  21. import numpy as np
  22. from huggingface_hub import snapshot_download
  23. from api.utils.file_utils import get_project_base_directory
  24. from deepdoc.vision import Recognizer
  25. from deepdoc.vision.operators import nms
  26. class LayoutRecognizer(Recognizer):
  27. labels = [
  28. "_background_",
  29. "Text",
  30. "Title",
  31. "Figure",
  32. "Figure caption",
  33. "Table",
  34. "Table caption",
  35. "Header",
  36. "Footer",
  37. "Reference",
  38. "Equation",
  39. ]
  40. def __init__(self, domain):
  41. try:
  42. model_dir = os.path.join(
  43. get_project_base_directory(),
  44. "rag/res/deepdoc")
  45. super().__init__(self.labels, domain, model_dir)
  46. except Exception:
  47. model_dir = snapshot_download(repo_id="InfiniFlow/deepdoc",
  48. local_dir=os.path.join(get_project_base_directory(), "rag/res/deepdoc"),
  49. local_dir_use_symlinks=False)
  50. super().__init__(self.labels, domain, model_dir)
  51. self.garbage_layouts = ["footer", "header", "reference"]
  52. def __call__(self, image_list, ocr_res, scale_factor=3,
  53. thr=0.2, batch_size=16, drop=True):
  54. def __is_garbage(b):
  55. patt = [r"^•+$", "^[0-9]{1,2} / ?[0-9]{1,2}$",
  56. r"^[0-9]{1,2} of [0-9]{1,2}$", "^http://[^ ]{12,}",
  57. "\\(cid *: *[0-9]+ *\\)"
  58. ]
  59. return any([re.search(p, b["text"]) for p in patt])
  60. layouts = super().__call__(image_list, thr, batch_size)
  61. # save_results(image_list, layouts, self.labels, output_dir='output/', threshold=0.7)
  62. assert len(image_list) == len(ocr_res)
  63. # Tag layout type
  64. boxes = []
  65. assert len(image_list) == len(layouts)
  66. garbages = {}
  67. page_layout = []
  68. for pn, lts in enumerate(layouts):
  69. bxs = ocr_res[pn]
  70. lts = [{"type": b["type"],
  71. "score": float(b["score"]),
  72. "x0": b["bbox"][0] / scale_factor, "x1": b["bbox"][2] / scale_factor,
  73. "top": b["bbox"][1] / scale_factor, "bottom": b["bbox"][-1] / scale_factor,
  74. "page_number": pn,
  75. } for b in lts if float(b["score"]) >= 0.4 or b["type"] not in self.garbage_layouts]
  76. lts = self.sort_Y_firstly(lts, np.mean(
  77. [lt["bottom"] - lt["top"] for lt in lts]) / 2)
  78. lts = self.layouts_cleanup(bxs, lts)
  79. page_layout.append(lts)
  80. # Tag layout type, layouts are ready
  81. def findLayout(ty):
  82. nonlocal bxs, lts, self
  83. lts_ = [lt for lt in lts if lt["type"] == ty]
  84. i = 0
  85. while i < len(bxs):
  86. if bxs[i].get("layout_type"):
  87. i += 1
  88. continue
  89. if __is_garbage(bxs[i]):
  90. bxs.pop(i)
  91. continue
  92. ii = self.find_overlapped_with_threashold(bxs[i], lts_,
  93. thr=0.4)
  94. if ii is None: # belong to nothing
  95. bxs[i]["layout_type"] = ""
  96. i += 1
  97. continue
  98. lts_[ii]["visited"] = True
  99. keep_feats = [
  100. lts_[
  101. ii]["type"] == "footer" and bxs[i]["bottom"] < image_list[pn].size[1] * 0.9 / scale_factor,
  102. lts_[
  103. ii]["type"] == "header" and bxs[i]["top"] > image_list[pn].size[1] * 0.1 / scale_factor,
  104. ]
  105. if drop and lts_[
  106. ii]["type"] in self.garbage_layouts and not any(keep_feats):
  107. if lts_[ii]["type"] not in garbages:
  108. garbages[lts_[ii]["type"]] = []
  109. garbages[lts_[ii]["type"]].append(bxs[i]["text"])
  110. bxs.pop(i)
  111. continue
  112. bxs[i]["layoutno"] = f"{ty}-{ii}"
  113. bxs[i]["layout_type"] = lts_[ii]["type"] if lts_[
  114. ii]["type"] != "equation" else "figure"
  115. i += 1
  116. for lt in ["footer", "header", "reference", "figure caption",
  117. "table caption", "title", "table", "text", "figure", "equation"]:
  118. findLayout(lt)
  119. # add box to figure layouts which has not text box
  120. for i, lt in enumerate(
  121. [lt for lt in lts if lt["type"] in ["figure", "equation"]]):
  122. if lt.get("visited"):
  123. continue
  124. lt = deepcopy(lt)
  125. del lt["type"]
  126. lt["text"] = ""
  127. lt["layout_type"] = "figure"
  128. lt["layoutno"] = f"figure-{i}"
  129. bxs.append(lt)
  130. boxes.extend(bxs)
  131. ocr_res = boxes
  132. garbag_set = set()
  133. for k in garbages.keys():
  134. garbages[k] = Counter(garbages[k])
  135. for g, c in garbages[k].items():
  136. if c > 1:
  137. garbag_set.add(g)
  138. ocr_res = [b for b in ocr_res if b["text"].strip() not in garbag_set]
  139. return ocr_res, page_layout
  140. def forward(self, image_list, thr=0.7, batch_size=16):
  141. return super().__call__(image_list, thr, batch_size)
  142. class LayoutRecognizer4YOLOv10(LayoutRecognizer):
  143. labels = [
  144. "title",
  145. "Text",
  146. "Reference",
  147. "Figure",
  148. "Figure caption",
  149. "Table",
  150. "Table caption",
  151. "Table caption",
  152. "Equation",
  153. "Figure caption",
  154. ]
  155. def __init__(self, domain):
  156. domain = "layout"
  157. super().__init__(domain)
  158. self.auto = False
  159. self.scaleFill = False
  160. self.scaleup = True
  161. self.stride = 32
  162. self.center = True
  163. def preprocess(self, image_list):
  164. inputs = []
  165. new_shape = self.input_shape # height, width
  166. for img in image_list:
  167. shape = img.shape[:2] # current shape [height, width]
  168. # Scale ratio (new / old)
  169. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  170. # Compute padding
  171. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  172. dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
  173. dw /= 2 # divide padding into 2 sides
  174. dh /= 2
  175. ww, hh = new_unpad
  176. img = np.array(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)).astype(np.float32)
  177. img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
  178. top, bottom = int(round(dh - 0.1)) if self.center else 0, int(round(dh + 0.1))
  179. left, right = int(round(dw - 0.1)) if self.center else 0, int(round(dw + 0.1))
  180. img = cv2.copyMakeBorder(
  181. img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)
  182. ) # add border
  183. img /= 255.0
  184. img = img.transpose(2, 0, 1)
  185. img = img[np.newaxis, :, :, :].astype(np.float32)
  186. inputs.append({self.input_names[0]: img, "scale_factor": [shape[1]/ww, shape[0]/hh, dw, dh]})
  187. return inputs
  188. def postprocess(self, boxes, inputs, thr):
  189. thr = 0.08
  190. boxes = np.squeeze(boxes)
  191. scores = boxes[:, 4]
  192. boxes = boxes[scores > thr, :]
  193. scores = scores[scores > thr]
  194. if len(boxes) == 0:
  195. return []
  196. class_ids = boxes[:, -1].astype(int)
  197. boxes = boxes[:, :4]
  198. boxes[:, 0] -= inputs["scale_factor"][2]
  199. boxes[:, 2] -= inputs["scale_factor"][2]
  200. boxes[:, 1] -= inputs["scale_factor"][3]
  201. boxes[:, 3] -= inputs["scale_factor"][3]
  202. input_shape = np.array([inputs["scale_factor"][0], inputs["scale_factor"][1], inputs["scale_factor"][0],
  203. inputs["scale_factor"][1]])
  204. boxes = np.multiply(boxes, input_shape, dtype=np.float32)
  205. unique_class_ids = np.unique(class_ids)
  206. indices = []
  207. for class_id in unique_class_ids:
  208. class_indices = np.where(class_ids == class_id)[0]
  209. class_boxes = boxes[class_indices, :]
  210. class_scores = scores[class_indices]
  211. class_keep_boxes = nms(class_boxes, class_scores, 0.45)
  212. indices.extend(class_indices[class_keep_boxes])
  213. return [{
  214. "type": self.label_list[class_ids[i]].lower(),
  215. "bbox": [float(t) for t in boxes[i].tolist()],
  216. "score": float(scores[i])
  217. } for i in indices]