serving_client.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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. import os
  15. import glob
  16. import base64
  17. import argparse
  18. from paddle_serving_client import Client
  19. from paddle_serving_client.proto import general_model_config_pb2 as m_config
  20. import google.protobuf.text_format
  21. parser = argparse.ArgumentParser(description="args for paddleserving")
  22. parser.add_argument(
  23. "--serving_client", type=str, help="the directory of serving_client")
  24. parser.add_argument("--image_dir", type=str)
  25. parser.add_argument("--image_file", type=str)
  26. parser.add_argument("--http_port", type=int, default=9997)
  27. parser.add_argument(
  28. "--threshold", type=float, default=0.5, help="Threshold of score.")
  29. args = parser.parse_args()
  30. def get_test_images(infer_dir, infer_img):
  31. """
  32. Get image path list in TEST mode
  33. """
  34. assert infer_img is not None or infer_dir is not None, \
  35. "--image_file or --image_dir should be set"
  36. assert infer_img is None or os.path.isfile(infer_img), \
  37. "{} is not a file".format(infer_img)
  38. assert infer_dir is None or os.path.isdir(infer_dir), \
  39. "{} is not a directory".format(infer_dir)
  40. # infer_img has a higher priority
  41. if infer_img and os.path.isfile(infer_img):
  42. return [infer_img]
  43. images = set()
  44. infer_dir = os.path.abspath(infer_dir)
  45. assert os.path.isdir(infer_dir), \
  46. "infer_dir {} is not a directory".format(infer_dir)
  47. exts = ['jpg', 'jpeg', 'png', 'bmp']
  48. exts += [ext.upper() for ext in exts]
  49. for ext in exts:
  50. images.update(glob.glob('{}/*.{}'.format(infer_dir, ext)))
  51. images = list(images)
  52. assert len(images) > 0, "no image found in {}".format(infer_dir)
  53. print("Found {} inference images in total.".format(len(images)))
  54. return images
  55. def postprocess(fetch_dict, fetch_vars, draw_threshold=0.5):
  56. result = []
  57. if "conv2d_441.tmp_1" in fetch_dict:
  58. heatmap = fetch_dict["conv2d_441.tmp_1"]
  59. print(heatmap)
  60. result.append(heatmap)
  61. else:
  62. bboxes = fetch_dict[fetch_vars[0]]
  63. for bbox in bboxes:
  64. if bbox[0] > -1 and bbox[1] > draw_threshold:
  65. print(f"{int(bbox[0])} {bbox[1]} "
  66. f"{bbox[2]} {bbox[3]} {bbox[4]} {bbox[5]}")
  67. result.append(f"{int(bbox[0])} {bbox[1]} "
  68. f"{bbox[2]} {bbox[3]} {bbox[4]} {bbox[5]}")
  69. return result
  70. def get_model_vars(client_config_dir):
  71. # read original serving_client_conf.prototxt
  72. client_config_file = os.path.join(client_config_dir,
  73. "serving_client_conf.prototxt")
  74. with open(client_config_file, 'r') as f:
  75. model_var = google.protobuf.text_format.Merge(
  76. str(f.read()), m_config.GeneralModelConfig())
  77. # modify feed_var to run core/general-server/op/
  78. [model_var.feed_var.pop() for _ in range(len(model_var.feed_var))]
  79. feed_var = m_config.FeedVar()
  80. feed_var.name = "input"
  81. feed_var.alias_name = "input"
  82. feed_var.is_lod_tensor = False
  83. feed_var.feed_type = 20
  84. feed_var.shape.extend([1])
  85. model_var.feed_var.extend([feed_var])
  86. with open(
  87. os.path.join(client_config_dir, "serving_client_conf_cpp.prototxt"),
  88. "w") as f:
  89. f.write(str(model_var))
  90. # get feed_vars/fetch_vars
  91. feed_vars = [var.name for var in model_var.feed_var]
  92. fetch_vars = [var.name for var in model_var.fetch_var]
  93. return feed_vars, fetch_vars
  94. if __name__ == '__main__':
  95. url = f"127.0.0.1:{args.http_port}"
  96. logid = 10000
  97. img_list = get_test_images(args.image_dir, args.image_file)
  98. feed_vars, fetch_vars = get_model_vars(args.serving_client)
  99. client = Client()
  100. client.load_client_config(
  101. os.path.join(args.serving_client, "serving_client_conf_cpp.prototxt"))
  102. client.connect([url])
  103. for img_file in img_list:
  104. with open(img_file, 'rb') as file:
  105. image_data = file.read()
  106. image = base64.b64encode(image_data).decode('utf8')
  107. fetch_dict = client.predict(
  108. feed={feed_vars[0]: image}, fetch=fetch_vars)
  109. result = postprocess(fetch_dict, fetch_vars, args.threshold)