doclayout.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. import abc
  2. import os.path
  3. import cv2
  4. import numpy as np
  5. import ast
  6. import onnx
  7. import onnxruntime
  8. from huggingface_hub import hf_hub_download
  9. from pdf2zh.config import ConfigManager
  10. class DocLayoutModel(abc.ABC):
  11. @staticmethod
  12. def load_onnx():
  13. model = OnnxModel.from_pretrained(
  14. repo_id="wybxc/DocLayout-YOLO-DocStructBench-onnx",
  15. filename="doclayout_yolo_docstructbench_imgsz1024.onnx",
  16. )
  17. return model
  18. @staticmethod
  19. def load_available():
  20. return DocLayoutModel.load_onnx()
  21. @property
  22. @abc.abstractmethod
  23. def stride(self) -> int:
  24. """Stride of the model input."""
  25. pass
  26. @abc.abstractmethod
  27. def predict(self, image, imgsz=1024, **kwargs) -> list:
  28. """
  29. Predict the layout of a document page.
  30. Args:
  31. image: The image of the document page.
  32. imgsz: Resize the image to this size. Must be a multiple of the stride.
  33. **kwargs: Additional arguments.
  34. """
  35. pass
  36. class YoloResult:
  37. """Helper class to store detection results from ONNX model."""
  38. def __init__(self, boxes, names):
  39. self.boxes = [YoloBox(data=d) for d in boxes]
  40. self.boxes.sort(key=lambda x: x.conf, reverse=True)
  41. self.names = names
  42. class YoloBox:
  43. """Helper class to store detection results from ONNX model."""
  44. def __init__(self, data):
  45. self.xyxy = data[:4]
  46. self.conf = data[-2]
  47. self.cls = data[-1]
  48. class OnnxModel(DocLayoutModel):
  49. def __init__(self, model_path: str):
  50. self.model_path = model_path
  51. model = onnx.load(model_path)
  52. metadata = {d.key: d.value for d in model.metadata_props}
  53. self._stride = ast.literal_eval(metadata["stride"])
  54. self._names = ast.literal_eval(metadata["names"])
  55. self.model = onnxruntime.InferenceSession(model.SerializeToString())
  56. @staticmethod
  57. def from_pretrained(repo_id: str, filename: str):
  58. if ConfigManager.get("USE_MODELSCOPE", "0") == "1":
  59. repo_mapping = {
  60. # Edit here to add more models
  61. "wybxc/DocLayout-YOLO-DocStructBench-onnx": "AI-ModelScope/DocLayout-YOLO-DocStructBench-onnx"
  62. }
  63. from modelscope import snapshot_download
  64. model_dir = snapshot_download(repo_mapping[repo_id])
  65. pth = os.path.join(model_dir, filename)
  66. else:
  67. pth = hf_hub_download(repo_id=repo_id, filename=filename, etag_timeout=1)
  68. return OnnxModel(pth)
  69. @property
  70. def stride(self):
  71. return self._stride
  72. def resize_and_pad_image(self, image, new_shape):
  73. """
  74. Resize and pad the image to the specified size, ensuring dimensions are multiples of stride.
  75. Parameters:
  76. - image: Input image
  77. - new_shape: Target size (integer or (height, width) tuple)
  78. - stride: Padding alignment stride, default 32
  79. Returns:
  80. - Processed image
  81. """
  82. if isinstance(new_shape, int):
  83. new_shape = (new_shape, new_shape)
  84. h, w = image.shape[:2]
  85. new_h, new_w = new_shape
  86. # Calculate scaling ratio
  87. r = min(new_h / h, new_w / w)
  88. resized_h, resized_w = int(round(h * r)), int(round(w * r))
  89. # Resize image
  90. image = cv2.resize(
  91. image, (resized_w, resized_h), interpolation=cv2.INTER_LINEAR
  92. )
  93. # Calculate padding size and align to stride multiple
  94. pad_w = (new_w - resized_w) % self.stride
  95. pad_h = (new_h - resized_h) % self.stride
  96. top, bottom = pad_h // 2, pad_h - pad_h // 2
  97. left, right = pad_w // 2, pad_w - pad_w // 2
  98. # Add padding
  99. image = cv2.copyMakeBorder(
  100. image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=(114, 114, 114)
  101. )
  102. return image
  103. def scale_boxes(self, img1_shape, boxes, img0_shape):
  104. """
  105. Rescales bounding boxes (in the format of xyxy by default) from the shape of the image they were originally
  106. specified in (img1_shape) to the shape of a different image (img0_shape).
  107. Args:
  108. img1_shape (tuple): The shape of the image that the bounding boxes are for,
  109. in the format of (height, width).
  110. boxes (torch.Tensor): the bounding boxes of the objects in the image, in the format of (x1, y1, x2, y2)
  111. img0_shape (tuple): the shape of the target image, in the format of (height, width).
  112. Returns:
  113. boxes (torch.Tensor): The scaled bounding boxes, in the format of (x1, y1, x2, y2)
  114. """
  115. # Calculate scaling ratio
  116. gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1])
  117. # Calculate padding size
  118. pad_x = round((img1_shape[1] - img0_shape[1] * gain) / 2 - 0.1)
  119. pad_y = round((img1_shape[0] - img0_shape[0] * gain) / 2 - 0.1)
  120. # Remove padding and scale boxes
  121. boxes[..., :4] = (boxes[..., :4] - [pad_x, pad_y, pad_x, pad_y]) / gain
  122. return boxes
  123. def predict(self, image, imgsz=1024, **kwargs):
  124. # Preprocess input image
  125. orig_h, orig_w = image.shape[:2]
  126. pix = self.resize_and_pad_image(image, new_shape=imgsz)
  127. pix = np.transpose(pix, (2, 0, 1)) # CHW
  128. pix = np.expand_dims(pix, axis=0) # BCHW
  129. pix = pix.astype(np.float32) / 255.0 # Normalize to [0, 1]
  130. new_h, new_w = pix.shape[2:]
  131. # Run inference
  132. preds = self.model.run(None, {"images": pix})[0]
  133. # Postprocess predictions
  134. preds = preds[preds[..., 4] > 0.25]
  135. preds[..., :4] = self.scale_boxes(
  136. (new_h, new_w), preds[..., :4], (orig_h, orig_w)
  137. )
  138. return [YoloResult(boxes=preds, names=self._names)]
  139. class ModelInstance:
  140. value: OnnxModel = None