web_service.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. # Copyright (c) 2021 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 paddle_serving_server.web_service import WebService, Op
  15. import logging
  16. import numpy as np
  17. import copy
  18. import cv2
  19. import base64
  20. # from paddle_serving_app.reader import OCRReader
  21. from ocr_reader import OCRReader, DetResizeForTest, ArgsParser
  22. from paddle_serving_app.reader import Sequential, ResizeByFactor
  23. from paddle_serving_app.reader import Div, Normalize, Transpose
  24. from paddle_serving_app.reader import DBPostProcess, FilterBoxes, GetRotateCropImage, SortedBoxes
  25. _LOGGER = logging.getLogger()
  26. class DetOp(Op):
  27. def init_op(self):
  28. self.det_preprocess = Sequential([
  29. DetResizeForTest(), Div(255),
  30. Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), Transpose(
  31. (2, 0, 1))
  32. ])
  33. self.filter_func = FilterBoxes(10, 10)
  34. self.post_func = DBPostProcess({
  35. "thresh": 0.3,
  36. "box_thresh": 0.6,
  37. "max_candidates": 1000,
  38. "unclip_ratio": 1.5,
  39. "min_size": 3
  40. })
  41. def preprocess(self, input_dicts, data_id, log_id):
  42. (_, input_dict), = input_dicts.items()
  43. data = base64.b64decode(input_dict["image"].encode('utf8'))
  44. self.raw_im = data
  45. data = np.fromstring(data, np.uint8)
  46. # Note: class variables(self.var) can only be used in process op mode
  47. im = cv2.imdecode(data, cv2.IMREAD_COLOR)
  48. self.ori_h, self.ori_w, _ = im.shape
  49. det_img = self.det_preprocess(im)
  50. _, self.new_h, self.new_w = det_img.shape
  51. return {"x": det_img[np.newaxis, :].copy()}, False, None, ""
  52. def postprocess(self, input_dicts, fetch_dict, data_id, log_id):
  53. det_out = list(fetch_dict.values())[0]
  54. ratio_list = [
  55. float(self.new_h) / self.ori_h, float(self.new_w) / self.ori_w
  56. ]
  57. dt_boxes_list = self.post_func(det_out, [ratio_list])
  58. dt_boxes = self.filter_func(dt_boxes_list[0], [self.ori_h, self.ori_w])
  59. out_dict = {"dt_boxes": dt_boxes, "image": self.raw_im}
  60. return out_dict, None, ""
  61. class RecOp(Op):
  62. def init_op(self):
  63. self.ocr_reader = OCRReader(
  64. char_dict_path="../../ppocr/utils/ppocr_keys_v1.txt")
  65. self.get_rotate_crop_image = GetRotateCropImage()
  66. self.sorted_boxes = SortedBoxes()
  67. def preprocess(self, input_dicts, data_id, log_id):
  68. (_, input_dict), = input_dicts.items()
  69. raw_im = input_dict["image"]
  70. data = np.frombuffer(raw_im, np.uint8)
  71. im = cv2.imdecode(data, cv2.IMREAD_COLOR)
  72. self.dt_list = input_dict["dt_boxes"]
  73. self.dt_list = self.sorted_boxes(self.dt_list)
  74. # deepcopy to save origin dt_boxes
  75. dt_boxes = copy.deepcopy(self.dt_list)
  76. feed_list = []
  77. img_list = []
  78. max_wh_ratio = 320 / 48.
  79. ## Many mini-batchs, the type of feed_data is list.
  80. max_batch_size = 6 # len(dt_boxes)
  81. # If max_batch_size is 0, skipping predict stage
  82. if max_batch_size == 0:
  83. return {}, True, None, ""
  84. boxes_size = len(dt_boxes)
  85. batch_size = boxes_size // max_batch_size
  86. rem = boxes_size % max_batch_size
  87. for bt_idx in range(0, batch_size + 1):
  88. imgs = None
  89. boxes_num_in_one_batch = 0
  90. if bt_idx == batch_size:
  91. if rem == 0:
  92. continue
  93. else:
  94. boxes_num_in_one_batch = rem
  95. elif bt_idx < batch_size:
  96. boxes_num_in_one_batch = max_batch_size
  97. else:
  98. _LOGGER.error("batch_size error, bt_idx={}, batch_size={}".
  99. format(bt_idx, batch_size))
  100. break
  101. start = bt_idx * max_batch_size
  102. end = start + boxes_num_in_one_batch
  103. img_list = []
  104. for box_idx in range(start, end):
  105. boximg = self.get_rotate_crop_image(im, dt_boxes[box_idx])
  106. img_list.append(boximg)
  107. h, w = boximg.shape[0:2]
  108. wh_ratio = w * 1.0 / h
  109. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  110. _, w, h = self.ocr_reader.resize_norm_img(img_list[0],
  111. max_wh_ratio).shape
  112. imgs = np.zeros((boxes_num_in_one_batch, 3, w, h)).astype('float32')
  113. for id, img in enumerate(img_list):
  114. norm_img = self.ocr_reader.resize_norm_img(img, max_wh_ratio)
  115. imgs[id] = norm_img
  116. feed = {"x": imgs.copy()}
  117. feed_list.append(feed)
  118. return feed_list, False, None, ""
  119. def postprocess(self, input_dicts, fetch_data, data_id, log_id):
  120. rec_list = []
  121. dt_num = len(self.dt_list)
  122. if isinstance(fetch_data, dict):
  123. if len(fetch_data) > 0:
  124. rec_batch_res = self.ocr_reader.postprocess(
  125. fetch_data, with_score=True)
  126. for res in rec_batch_res:
  127. rec_list.append(res)
  128. elif isinstance(fetch_data, list):
  129. for one_batch in fetch_data:
  130. one_batch_res = self.ocr_reader.postprocess(
  131. one_batch, with_score=True)
  132. for res in one_batch_res:
  133. rec_list.append(res)
  134. result_list = []
  135. for i in range(dt_num):
  136. text = rec_list[i]
  137. dt_box = self.dt_list[i]
  138. if text[1] >= 0.5:
  139. result_list.append([text, dt_box.tolist()])
  140. res = {"result": str(result_list)}
  141. return res, None, ""
  142. class OcrService(WebService):
  143. def get_pipeline_response(self, read_op):
  144. det_op = DetOp(name="det", input_ops=[read_op])
  145. rec_op = RecOp(name="rec", input_ops=[det_op])
  146. return rec_op
  147. uci_service = OcrService(name="ocr")
  148. FLAGS = ArgsParser().parse_args()
  149. uci_service.prepare_pipeline_config(yml_dict=FLAGS.conf_dict)
  150. uci_service.run_service()