module.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  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 __future__ import absolute_import
  15. from __future__ import division
  16. from __future__ import print_function
  17. import os
  18. import sys
  19. sys.path.insert(0, ".")
  20. import copy
  21. import time
  22. import paddlehub
  23. from paddlehub.common.logger import logger
  24. from paddlehub.module.module import moduleinfo, runnable, serving
  25. import cv2
  26. import paddlehub as hub
  27. from tools.infer.utility import base64_to_cv2
  28. from ppstructure.layout.predict_layout import LayoutPredictor as _LayoutPredictor
  29. from ppstructure.utility import parse_args
  30. from deploy.hubserving.structure_layout.params import read_params
  31. @moduleinfo(
  32. name="structure_layout",
  33. version="1.0.0",
  34. summary="PP-Structure layout service",
  35. author="paddle-dev",
  36. author_email="paddle-dev@baidu.com",
  37. type="cv/structure_layout")
  38. class LayoutPredictor(hub.Module):
  39. def _initialize(self, use_gpu=False, enable_mkldnn=False):
  40. """
  41. initialize with the necessary elements
  42. """
  43. cfg = self.merge_configs()
  44. cfg.use_gpu = use_gpu
  45. if use_gpu:
  46. try:
  47. _places = os.environ["CUDA_VISIBLE_DEVICES"]
  48. int(_places[0])
  49. print("use gpu: ", use_gpu)
  50. print("CUDA_VISIBLE_DEVICES: ", _places)
  51. cfg.gpu_mem = 8000
  52. except:
  53. raise RuntimeError(
  54. "Environment Variable CUDA_VISIBLE_DEVICES is not set correctly. If you wanna use gpu, please set CUDA_VISIBLE_DEVICES via export CUDA_VISIBLE_DEVICES=cuda_device_id."
  55. )
  56. cfg.ir_optim = True
  57. cfg.enable_mkldnn = enable_mkldnn
  58. self.layout_predictor = _LayoutPredictor(cfg)
  59. def merge_configs(self):
  60. # deafult cfg
  61. backup_argv = copy.deepcopy(sys.argv)
  62. sys.argv = sys.argv[:1]
  63. cfg = parse_args()
  64. update_cfg_map = vars(read_params())
  65. for key in update_cfg_map:
  66. cfg.__setattr__(key, update_cfg_map[key])
  67. sys.argv = copy.deepcopy(backup_argv)
  68. return cfg
  69. def read_images(self, paths=[]):
  70. images = []
  71. for img_path in paths:
  72. assert os.path.isfile(
  73. img_path), "The {} isn't a valid file.".format(img_path)
  74. img = cv2.imread(img_path)
  75. if img is None:
  76. logger.info("error in loading image:{}".format(img_path))
  77. continue
  78. images.append(img)
  79. return images
  80. def predict(self, images=[], paths=[]):
  81. """
  82. Get the chinese texts in the predicted images.
  83. Args:
  84. images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
  85. paths (list[str]): The paths of images. If paths not images
  86. Returns:
  87. res (list): The layout results of images.
  88. """
  89. if images != [] and isinstance(images, list) and paths == []:
  90. predicted_data = images
  91. elif images == [] and isinstance(paths, list) and paths != []:
  92. predicted_data = self.read_images(paths)
  93. else:
  94. raise TypeError("The input data is inconsistent with expectations.")
  95. assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
  96. all_results = []
  97. for img in predicted_data:
  98. if img is None:
  99. logger.info("error in loading image")
  100. all_results.append([])
  101. continue
  102. starttime = time.time()
  103. res, _ = self.layout_predictor(img)
  104. elapse = time.time() - starttime
  105. logger.info("Predict time: {}".format(elapse))
  106. for item in res:
  107. item['bbox'] = item['bbox'].tolist()
  108. all_results.append({'layout': res})
  109. return all_results
  110. @serving
  111. def serving_method(self, images, **kwargs):
  112. """
  113. Run as a service.
  114. """
  115. images_decode = [base64_to_cv2(image) for image in images]
  116. results = self.predict(images_decode, **kwargs)
  117. return results
  118. if __name__ == '__main__':
  119. layout = LayoutPredictor()
  120. layout._initialize()
  121. image_path = ['./ppstructure/docs/table/1.png']
  122. res = layout.predict(paths=image_path)
  123. print(res)