ocr_web_server.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. # Copyright (c) 2020 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_client import Client
  15. import cv2
  16. import sys
  17. import numpy as np
  18. import os
  19. from paddle_serving_client import Client
  20. from paddle_serving_app.reader import Sequential, URL2Image, ResizeByFactor
  21. from paddle_serving_app.reader import Div, Normalize, Transpose
  22. from paddle_serving_app.reader import DBPostProcess, FilterBoxes, GetRotateCropImage, SortedBoxes
  23. from ocr_reader import OCRReader
  24. try:
  25. from paddle_serving_server_gpu.web_service import WebService
  26. except ImportError:
  27. from paddle_serving_server.web_service import WebService
  28. from paddle_serving_app.local_predict import LocalPredictor
  29. import time
  30. import re
  31. import base64
  32. class OCRService(WebService):
  33. def init_det_debugger(self, det_model_config):
  34. self.det_preprocess = Sequential([
  35. ResizeByFactor(32, 960), Div(255),
  36. Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), Transpose(
  37. (2, 0, 1))
  38. ])
  39. self.det_client = LocalPredictor()
  40. if sys.argv[1] == 'gpu':
  41. self.det_client.load_model_config(
  42. det_model_config, use_gpu=True, gpu_id=0)
  43. elif sys.argv[1] == 'cpu':
  44. self.det_client.load_model_config(det_model_config)
  45. self.ocr_reader = OCRReader(
  46. char_dict_path="../../../ppocr/utils/ppocr_keys_v1.txt")
  47. def preprocess(self, feed=[], fetch=[]):
  48. data = base64.b64decode(feed[0]["image"].encode('utf8'))
  49. data = np.fromstring(data, np.uint8)
  50. im = cv2.imdecode(data, cv2.IMREAD_COLOR)
  51. ori_h, ori_w, _ = im.shape
  52. det_img = self.det_preprocess(im)
  53. _, new_h, new_w = det_img.shape
  54. det_img = det_img[np.newaxis, :]
  55. det_img = det_img.copy()
  56. det_out = self.det_client.predict(
  57. feed={"x": det_img}, fetch=["save_infer_model/scale_0.tmp_1"], batch=True)
  58. filter_func = FilterBoxes(10, 10)
  59. post_func = DBPostProcess({
  60. "thresh": 0.3,
  61. "box_thresh": 0.5,
  62. "max_candidates": 1000,
  63. "unclip_ratio": 1.5,
  64. "min_size": 3
  65. })
  66. sorted_boxes = SortedBoxes()
  67. ratio_list = [float(new_h) / ori_h, float(new_w) / ori_w]
  68. dt_boxes_list = post_func(det_out["save_infer_model/scale_0.tmp_1"], [ratio_list])
  69. dt_boxes = filter_func(dt_boxes_list[0], [ori_h, ori_w])
  70. dt_boxes = sorted_boxes(dt_boxes)
  71. get_rotate_crop_image = GetRotateCropImage()
  72. img_list = []
  73. max_wh_ratio = 0
  74. for i, dtbox in enumerate(dt_boxes):
  75. boximg = get_rotate_crop_image(im, dt_boxes[i])
  76. img_list.append(boximg)
  77. h, w = boximg.shape[0:2]
  78. wh_ratio = w * 1.0 / h
  79. max_wh_ratio = max(max_wh_ratio, wh_ratio)
  80. if len(img_list) == 0:
  81. return [], []
  82. _, w, h = self.ocr_reader.resize_norm_img(img_list[0],
  83. max_wh_ratio).shape
  84. imgs = np.zeros((len(img_list), 3, w, h)).astype('float32')
  85. for id, img in enumerate(img_list):
  86. norm_img = self.ocr_reader.resize_norm_img(img, max_wh_ratio)
  87. imgs[id] = norm_img
  88. feed = {"x": imgs.copy()}
  89. fetch = ["save_infer_model/scale_0.tmp_1"]
  90. return feed, fetch, True
  91. def postprocess(self, feed={}, fetch=[], fetch_map=None):
  92. rec_res = self.ocr_reader.postprocess(fetch_map, with_score=True)
  93. res_lst = []
  94. for res in rec_res:
  95. res_lst.append(res[0])
  96. res = {"res": res_lst}
  97. return res
  98. ocr_service = OCRService(name="ocr")
  99. ocr_service.load_model_config("../ppocr_rec_mobile_2.0_serving")
  100. ocr_service.prepare_server(workdir="workdir", port=9292)
  101. ocr_service.init_det_debugger(det_model_config="../ppocr_det_mobile_2.0_serving")
  102. if sys.argv[1] == 'gpu':
  103. ocr_service.set_gpus("0")
  104. ocr_service.run_debugger_service(gpu=True)
  105. elif sys.argv[1] == 'cpu':
  106. ocr_service.run_debugger_service()
  107. ocr_service.run_web_service()