module.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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 paddlehub
  22. from paddlehub.common.logger import logger
  23. from paddlehub.module.module import moduleinfo, runnable, serving
  24. import cv2
  25. import paddlehub as hub
  26. from tools.infer.utility import base64_to_cv2
  27. from tools.infer.predict_rec import TextRecognizer
  28. from tools.infer.utility import parse_args
  29. from deploy.hubserving.ocr_rec.params import read_params
  30. @moduleinfo(
  31. name="ocr_rec",
  32. version="1.0.0",
  33. summary="ocr recognition service",
  34. author="paddle-dev",
  35. author_email="paddle-dev@baidu.com",
  36. type="cv/text_recognition")
  37. class OCRRec(hub.Module):
  38. def _initialize(self, use_gpu=False, enable_mkldnn=False):
  39. """
  40. initialize with the necessary elements
  41. """
  42. cfg = self.merge_configs()
  43. cfg.use_gpu = use_gpu
  44. if use_gpu:
  45. try:
  46. _places = os.environ["CUDA_VISIBLE_DEVICES"]
  47. int(_places[0])
  48. print("use gpu: ", use_gpu)
  49. print("CUDA_VISIBLE_DEVICES: ", _places)
  50. cfg.gpu_mem = 8000
  51. except:
  52. raise RuntimeError(
  53. "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."
  54. )
  55. cfg.ir_optim = True
  56. cfg.enable_mkldnn = enable_mkldnn
  57. self.text_recognizer = TextRecognizer(cfg)
  58. def merge_configs(self, ):
  59. # deafult cfg
  60. backup_argv = copy.deepcopy(sys.argv)
  61. sys.argv = sys.argv[:1]
  62. cfg = parse_args()
  63. update_cfg_map = vars(read_params())
  64. for key in update_cfg_map:
  65. cfg.__setattr__(key, update_cfg_map[key])
  66. sys.argv = copy.deepcopy(backup_argv)
  67. return cfg
  68. def read_images(self, paths=[]):
  69. images = []
  70. for img_path in paths:
  71. assert os.path.isfile(
  72. img_path), "The {} isn't a valid file.".format(img_path)
  73. img = cv2.imread(img_path)
  74. if img is None:
  75. logger.info("error in loading image:{}".format(img_path))
  76. continue
  77. images.append(img)
  78. return images
  79. def predict(self, images=[], paths=[]):
  80. """
  81. Get the text box in the predicted images.
  82. Args:
  83. images (list(numpy.ndarray)): images data, shape of each is [H, W, C]. If images not paths
  84. paths (list[str]): The paths of images. If paths not images
  85. Returns:
  86. res (list): The result of text detection box and save path of images.
  87. """
  88. if images != [] and isinstance(images, list) and paths == []:
  89. predicted_data = images
  90. elif images == [] and isinstance(paths, list) and paths != []:
  91. predicted_data = self.read_images(paths)
  92. else:
  93. raise TypeError("The input data is inconsistent with expectations.")
  94. assert predicted_data != [], "There is not any image to be predicted. Please check the input data."
  95. img_list = []
  96. for img in predicted_data:
  97. if img is None:
  98. continue
  99. img_list.append(img)
  100. rec_res_final = []
  101. try:
  102. rec_res, predict_time = self.text_recognizer(img_list)
  103. for dno in range(len(rec_res)):
  104. text, score = rec_res[dno]
  105. rec_res_final.append({
  106. 'text': text,
  107. 'confidence': float(score),
  108. })
  109. except Exception as e:
  110. print(e)
  111. return [[]]
  112. return [rec_res_final]
  113. @serving
  114. def serving_method(self, images, **kwargs):
  115. """
  116. Run as a service.
  117. """
  118. images_decode = [base64_to_cv2(image) for image in images]
  119. results = self.predict(images_decode, **kwargs)
  120. return results
  121. if __name__ == '__main__':
  122. ocr = OCRRec()
  123. ocr._initialize()
  124. image_path = [
  125. './doc/imgs_words/ch/word_1.jpg',
  126. './doc/imgs_words/ch/word_2.jpg',
  127. './doc/imgs_words/ch/word_3.jpg',
  128. ]
  129. res = ocr.predict(paths=image_path)
  130. print(res)