pipeline.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. import os
  15. import cv2
  16. from ..base import BasePipeline
  17. from ...modules.text_detection.model_list import MODELS as text_det_models
  18. from ...modules.text_recognition.model_list import MODELS as text_rec_models
  19. from ...modules import create_model, PaddleInferenceOption
  20. from ...modules.text_detection import transforms as text_det_T
  21. from .utils import draw_ocr_box_txt
  22. class OCRPipeline(BasePipeline):
  23. """OCR Pipeline"""
  24. entities = "OCR"
  25. def __init__(
  26. self,
  27. text_det_model_name=None,
  28. text_rec_model_name=None,
  29. text_det_model_dir=None,
  30. text_rec_model_dir=None,
  31. text_det_kernel_option=None,
  32. text_rec_kernel_option=None,
  33. output="./",
  34. device="gpu",
  35. **kwargs,
  36. ):
  37. super().__init__(**kwargs)
  38. self.text_det_model_name = text_det_model_name
  39. self.text_rec_model_name = text_rec_model_name
  40. self.text_det_model_dir = text_det_model_dir
  41. self.text_rec_model_dir = text_rec_model_dir
  42. self.output = output
  43. self.device = device
  44. self.text_det_kernel_option = text_det_kernel_option
  45. self.text_rec_kernel_option = text_rec_kernel_option
  46. if self.text_det_model_name in ['PP-OCRv4_server_seal_det', 'PP-OCRv4_mobile_seal_det']:
  47. self.task = "poly"
  48. else:
  49. self.task = "quad"
  50. if (
  51. self.text_det_model_name is not None
  52. and self.text_rec_model_name is not None
  53. ):
  54. self.load_model()
  55. def check_model_name(self):
  56. """check that model name is valid"""
  57. assert (
  58. self.text_det_model_name in text_det_models
  59. ), f"The model name({self.text_det_model_name}) error. \
  60. Only support: {text_det_models}."
  61. assert (
  62. self.text_rec_model_name in text_rec_models
  63. ), f"The model name({self.text_rec_model_name}) error. \
  64. Only support: {text_rec_models}."
  65. def load_model(self):
  66. """load model predictor"""
  67. self.check_model_name()
  68. text_det_kernel_option = (
  69. self.get_kernel_option()
  70. if self.text_det_kernel_option is None
  71. else self.text_det_kernel_option
  72. )
  73. text_rec_kernel_option = (
  74. self.get_kernel_option()
  75. if self.text_rec_kernel_option is None
  76. else self.text_rec_kernel_option
  77. )
  78. if self.task == "poly":
  79. text_det_post_transforms = [
  80. text_det_T.DBPostProcess(
  81. thresh=0.2,
  82. box_thresh=0.6,
  83. max_candidates=1000,
  84. unclip_ratio=1.5,
  85. use_dilation=False,
  86. score_mode="fast",
  87. box_type="poly",
  88. ),
  89. # TODO
  90. text_det_T.CropByPolys(det_box_type="poly"),
  91. ]
  92. else:
  93. text_det_post_transforms = [
  94. text_det_T.DBPostProcess(
  95. thresh=0.3,
  96. box_thresh=0.6,
  97. max_candidates=1000,
  98. unclip_ratio=1.5,
  99. use_dilation=False,
  100. score_mode="fast",
  101. box_type="quad",
  102. ),
  103. # TODO
  104. text_det_T.CropByPolys(det_box_type="quad"),
  105. ]
  106. self.text_det_model = create_model(
  107. self.text_det_model_name,
  108. self.text_det_model_dir,
  109. kernel_option=text_det_kernel_option,
  110. post_transforms=text_det_post_transforms,
  111. )
  112. self.text_rec_model = create_model(
  113. self.text_rec_model_name,
  114. self.text_rec_model_dir,
  115. kernel_option=text_rec_kernel_option,
  116. disable_print=self.disable_print,
  117. disable_save=self.disable_save,
  118. )
  119. def predict(self, input):
  120. """predict"""
  121. result = self.text_det_model.predict(input)
  122. all_rec_result = []
  123. for i, img in enumerate(result["sub_imgs"]):
  124. rec_result = self.text_rec_model.predict({"image": img})
  125. all_rec_result.append(rec_result["rec_text"][0])
  126. result["rec_text"] = all_rec_result
  127. if self.output is not None:
  128. draw_img = draw_ocr_box_txt(
  129. result["original_image"], result["dt_polys"], result["rec_text"]
  130. )
  131. fn = os.path.basename(result["input_path"])
  132. cv2.imwrite(
  133. os.path.join(self.output, fn),
  134. draw_img[:, :, ::-1],
  135. )
  136. return result
  137. def update_model(self, model_name_list, model_dir_list):
  138. """update model
  139. Args:
  140. model_name_list (list): list of model name.
  141. model_dir_list (list): list of model directory.
  142. """
  143. assert len(model_name_list) == 2
  144. self.text_det_model_name = model_name_list[0]
  145. self.text_rec_model_name = model_name_list[1]
  146. if model_dir_list:
  147. assert len(model_dir_list) == 2
  148. self.text_det_model_dir = model_dir_list[0]
  149. self.text_rec_model_dir = model_dir_list[1]
  150. def get_kernel_option(self):
  151. """get kernel option"""
  152. kernel_option = PaddleInferenceOption()
  153. kernel_option.set_device(self.device)
  154. return kernel_option
  155. def get_input_keys(self):
  156. """get dict keys of input argument input"""
  157. return self.text_det_model.get_input_keys()