pipeline.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from ..base import BasePipeline
  15. from typing import Any, Dict, Optional
  16. from scipy.ndimage import rotate
  17. from .result import DocPreprocessorResult
  18. ########## [TODO]后续需要更新路径
  19. from ...components.transforms import ReadImage
  20. class DocPreprocessorPipeline(BasePipeline):
  21. """Doc Preprocessor Pipeline"""
  22. entities = "doc_preprocessor"
  23. def __init__(
  24. self,
  25. config,
  26. device=None,
  27. pp_option=None,
  28. use_hpip: bool = False,
  29. hpi_params: Optional[Dict[str, Any]] = None,
  30. ):
  31. super().__init__(
  32. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_params=hpi_params
  33. )
  34. self.use_doc_orientation_classify = True
  35. if "use_doc_orientation_classify" in config:
  36. self.use_doc_orientation_classify = config["use_doc_orientation_classify"]
  37. self.use_doc_unwarping = True
  38. if "use_doc_unwarping" in config:
  39. self.use_doc_unwarping = config["use_doc_unwarping"]
  40. if self.use_doc_orientation_classify:
  41. doc_ori_classify_config = config["SubModules"]["DocOrientationClassify"]
  42. self.doc_ori_classify_model = self.create_model(doc_ori_classify_config)
  43. if self.use_doc_unwarping:
  44. doc_unwarping_config = config["SubModules"]["DocUnwarping"]
  45. self.doc_unwarping_model = self.create_model(doc_unwarping_config)
  46. self.img_reader = ReadImage(format="BGR")
  47. def rotate_image(self, image_array, rotate_angle):
  48. """rotate image"""
  49. assert (
  50. rotate_angle >= 0 and rotate_angle < 360
  51. ), "rotate_angle must in [0-360), but get {rotate_angle}."
  52. return rotate(image_array, rotate_angle, reshape=True)
  53. def check_input_params(self, input_params):
  54. if (
  55. input_params["use_doc_orientation_classify"]
  56. and not self.use_doc_orientation_classify
  57. ):
  58. raise ValueError(
  59. "The model for doc orientation classify is not initialized."
  60. )
  61. if input_params["use_doc_unwarping"] and not self.use_doc_unwarping:
  62. raise ValueError("The model for doc unwarping is not initialized.")
  63. return
  64. def predict(
  65. self,
  66. input,
  67. use_doc_orientation_classify=True,
  68. use_doc_unwarping=False,
  69. **kwargs
  70. ):
  71. if not isinstance(input, list):
  72. input_list = [input]
  73. else:
  74. input_list = input
  75. input_params = {
  76. "use_doc_orientation_classify": use_doc_orientation_classify,
  77. "use_doc_unwarping": use_doc_unwarping,
  78. }
  79. self.check_input_params(input_params)
  80. img_id = 1
  81. for input in input_list:
  82. if isinstance(input, str):
  83. image_array = next(self.img_reader(input))[0]["img"]
  84. else:
  85. image_array = input
  86. assert len(image_array.shape) == 3
  87. if input_params["use_doc_orientation_classify"]:
  88. pred = next(self.doc_ori_classify_model(image_array))
  89. angle = int(pred["label_names"][0])
  90. rot_img = self.rotate_image(image_array, angle)
  91. else:
  92. angle = -1
  93. rot_img = image_array
  94. if input_params["use_doc_unwarping"]:
  95. output_img = next(self.doc_unwarping_model(rot_img))["doctr_img"]
  96. else:
  97. output_img = rot_img
  98. single_img_res = {
  99. "input_image": image_array,
  100. "input_params": input_params,
  101. "angle": angle,
  102. "rot_img": rot_img,
  103. "output_img": output_img,
  104. "img_id": img_id,
  105. }
  106. img_id += 1
  107. yield DocPreprocessorResult(single_img_res)