Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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"^•+$", r"(版权归©|免责条款|地址[::])", r"\.{3,}", "^[0-9]{1,2} / ?[0-9]{1,2}$",
  56. r"^[0-9]{1,2} of [0-9]{1,2}$", "^http://[^ ]{12,}",
  57. "(资料|数据)来源[::]", "[0-9a-z._-]+@[a-z0-9-]+\\.[a-z]{2,3}",
  58. "\\(cid *: *[0-9]+ *\\)"
  59. ]
  60. return any([re.search(p, b["text"]) for p in patt])
  61. layouts = super().__call__(image_list, thr, batch_size)
  62. # save_results(image_list, layouts, self.labels, output_dir='output/', threshold=0.7)
  63. assert len(image_list) == len(ocr_res)
  64. # Tag layout type
  65. boxes = []
  66. assert len(image_list) == len(layouts)
  67. garbages = {}
  68. page_layout = []
  69. for pn, lts in enumerate(layouts):
  70. bxs = ocr_res[pn]
  71. lts = [{"type": b["type"],
  72. "score": float(b["score"]),
  73. "x0": b["bbox"][0] / scale_factor, "x1": b["bbox"][2] / scale_factor,
  74. "top": b["bbox"][1] / scale_factor, "bottom": b["bbox"][-1] / scale_factor,
  75. "page_number": pn,
  76. } for b in lts if float(b["score"]) >= 0.4 or b["type"] not in self.garbage_layouts]
  77. lts = self.sort_Y_firstly(lts, np.mean(
  78. [lt["bottom"] - lt["top"] for lt in lts]) / 2)
  79. lts = self.layouts_cleanup(bxs, lts)
  80. page_layout.append(lts)
  81. # Tag layout type, layouts are ready
  82. def findLayout(ty):
  83. nonlocal bxs, lts, self
  84. lts_ = [lt for lt in lts if lt["type"] == ty]
  85. i = 0
  86. while i < len(bxs):
  87. if bxs[i].get("layout_type"):
  88. i += 1
  89. continue
  90. if __is_garbage(bxs[i]):
  91. bxs.pop(i)
  92. continue
  93. ii = self.find_overlapped_with_threashold(bxs[i], lts_,
  94. thr=0.4)
  95. if ii is None: # belong to nothing
  96. bxs[i]["layout_type"] = ""
  97. i += 1
  98. continue
  99. lts_[ii]["visited"] = True
  100. keep_feats = [
  101. lts_[
  102. ii]["type"] == "footer" and bxs[i]["bottom"] < image_list[pn].size[1] * 0.9 / scale_factor,
  103. lts_[
  104. ii]["type"] == "header" and bxs[i]["top"] > image_list[pn].size[1] * 0.1 / scale_factor,
  105. ]
  106. if drop and lts_[
  107. ii]["type"] in self.garbage_layouts and not any(keep_feats):
  108. if lts_[ii]["type"] not in garbages:
  109. garbages[lts_[ii]["type"]] = []
  110. garbages[lts_[ii]["type"]].append(bxs[i]["text"])
  111. bxs.pop(i)
  112. continue
  113. bxs[i]["layoutno"] = f"{ty}-{ii}"
  114. bxs[i]["layout_type"] = lts_[ii]["type"] if lts_[
  115. ii]["type"] != "equation" else "figure"
  116. i += 1
  117. for lt in ["footer", "header", "reference", "figure caption",
  118. "table caption", "title", "table", "text", "figure", "equation"]:
  119. findLayout(lt)
  120. # add box to figure layouts which has not text box
  121. for i, lt in enumerate(
  122. [lt for lt in lts if lt["type"] in ["figure", "equation"]]):
  123. if lt.get("visited"):
  124. continue
  125. lt = deepcopy(lt)
  126. del lt["type"]
  127. lt["text"] = ""
  128. lt["layout_type"] = "figure"
  129. lt["layoutno"] = f"figure-{i}"
  130. bxs.append(lt)
  131. boxes.extend(bxs)
  132. ocr_res = boxes
  133. garbag_set = set()
  134. for k in garbages.keys():
  135. garbages[k] = Counter(garbages[k])
  136. for g, c in garbages[k].items():
  137. if c > 1:
  138. garbag_set.add(g)
  139. ocr_res = [b for b in ocr_res if b["text"].strip() not in garbag_set]
  140. return ocr_res, page_layout
  141. def forward(self, image_list, thr=0.7, batch_size=16):
  142. return super().__call__(image_list, thr, batch_size)
  143. class LayoutRecognizer4YOLOv10(LayoutRecognizer):
  144. labels = [
  145. "title",
  146. "Text",
  147. "Reference",
  148. "Figure",
  149. "Figure caption",
  150. "Table",
  151. "Table caption",
  152. "Table caption",
  153. "Equation",
  154. "Figure caption",
  155. ]
  156. def __init__(self, domain):
  157. domain = "layout"
  158. super().__init__(domain)
  159. self.auto = False
  160. self.scaleFill = False
  161. self.scaleup = True
  162. self.stride = 32
  163. self.center = True
  164. def preprocess(self, image_list):
  165. inputs = []
  166. new_shape = self.input_shape # height, width
  167. for img in image_list:
  168. shape = img.shape[:2]# current shape [height, width]
  169. # Scale ratio (new / old)
  170. r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
  171. # Compute padding
  172. new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
  173. dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
  174. dw /= 2 # divide padding into 2 sides
  175. dh /= 2
  176. ww, hh = new_unpad
  177. img = np.array(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)).astype(np.float32)
  178. img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
  179. top, bottom = int(round(dh - 0.1)) if self.center else 0, int(round(dh + 0.1))
  180. left, right = int(round(dw - 0.1)) if self.center else 0, int(round(dw + 0.1))
  181. img = cv2.copyMakeBorder(
  182. img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)
  183. ) # add border
  184. img /= 255.0
  185. img = img.transpose(2, 0, 1)
  186. img = img[np.newaxis, :, :, :].astype(np.float32)
  187. inputs.append({self.input_names[0]: img, "scale_factor": [shape[1]/ww, shape[0]/hh, dw, dh]})
  188. return inputs
  189. def postprocess(self, boxes, inputs, thr):
  190. thr = 0.08
  191. boxes = np.squeeze(boxes)
  192. scores = boxes[:, 4]
  193. boxes = boxes[scores > thr, :]
  194. scores = scores[scores > thr]
  195. if len(boxes) == 0:
  196. return []
  197. class_ids = boxes[:, -1].astype(int)
  198. boxes = boxes[:, :4]
  199. boxes[:, 0] -= inputs["scale_factor"][2]
  200. boxes[:, 2] -= inputs["scale_factor"][2]
  201. boxes[:, 1] -= inputs["scale_factor"][3]
  202. boxes[:, 3] -= inputs["scale_factor"][3]
  203. input_shape = np.array([inputs["scale_factor"][0], inputs["scale_factor"][1], inputs["scale_factor"][0],
  204. inputs["scale_factor"][1]])
  205. boxes = np.multiply(boxes, input_shape, dtype=np.float32)
  206. unique_class_ids = np.unique(class_ids)
  207. indices = []
  208. for class_id in unique_class_ids:
  209. class_indices = np.where(class_ids == class_id)[0]
  210. class_boxes = boxes[class_indices, :]
  211. class_scores = scores[class_indices]
  212. class_keep_boxes = nms(class_boxes, class_scores, 0.45)
  213. indices.extend(class_indices[class_keep_boxes])
  214. return [{
  215. "type": self.label_list[class_ids[i]].lower(),
  216. "bbox": [float(t) for t in boxes[i].tolist()],
  217. "score": float(scores[i])
  218. } for i in indices]