You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tensorflow_inference_service.py 6.0 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. """
  2. Copyright 2020 Tianshu AI Platform. All Rights Reserved.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. """
  13. import tensorflow as tf
  14. import requests
  15. import numpy as np
  16. from imagenet1000_clsidx_to_labels import clsidx_2_labels
  17. from service.abstract_inference_service import AbstractInferenceService
  18. from utils.imagenet_preprocessing_utils import preprocess_input
  19. from logger import Logger
  20. from PIL import Image
  21. from io import BytesIO
  22. log = Logger().logger
  23. class TensorflowInferenceService(AbstractInferenceService):
  24. """
  25. tensorflow 框架推理service
  26. """
  27. def __init__(self, args):
  28. super().__init__()
  29. self.session = tf.compat.v1.Session(graph=tf.Graph())
  30. self.args = args
  31. self.model_name = args.model_name
  32. self.model_path = args.model_path
  33. self.signature_input_keys = []
  34. self.signature_input_tensor_names = []
  35. self.signature_output_keys = []
  36. self.signature_output_tensor_names = []
  37. self.input_info_from_signature = {}
  38. self.output_info_from_signature = {}
  39. self.load_model()
  40. def load_image(self, image_path):
  41. if image_path.startswith("http"):
  42. response = requests.get(image_path)
  43. response = response.content
  44. BytesIOObj = BytesIO()
  45. BytesIOObj.write(response)
  46. im = Image.open(BytesIOObj)
  47. else:
  48. im = Image.open(image_path)
  49. # signature中读取图片大小做resize
  50. image_shape_from_signature = list(self.input_info_from_signature.values())[0]["shape"]
  51. height = image_shape_from_signature[1]
  52. width = image_shape_from_signature[2]
  53. im = im.resize((height, width))
  54. im = im.convert('RGB') # 有的图像是单通道的,不加转换会报错
  55. im = np.array(im).astype('float32')
  56. return np.ascontiguousarray(im, 'float32')
  57. def load_model(self):
  58. log.info("===============> start load tensorflow model :" + self.model_path + " <===============")
  59. meta_graph = tf.compat.v1.saved_model.load(
  60. self.session, [tf.compat.v1.saved_model.tag_constants.SERVING], self.model_path)
  61. # 加载模型之前先校验用户传入signature name
  62. if self.args.signature_name not in meta_graph.signature_def:
  63. log.error("==============> Invalid signature name <==================")
  64. # 从signature中获取meta graph中输入和输出的节点信息
  65. signature = meta_graph.signature_def[self.args.signature_name]
  66. input_keys, input_tensor_names = get_tensors(signature.inputs)
  67. output_keys, output_tensor_names = get_tensors(signature.outputs)
  68. self.signature_input_keys = input_keys
  69. self.signature_output_keys = output_keys
  70. self.signature_input_tensor_names = input_tensor_names
  71. self.signature_output_tensor_names = output_tensor_names
  72. self.input_info_from_signature = get_tensor_info_from_signature(signature.inputs)
  73. self.output_info_from_signature = get_tensor_info_from_signature(signature.outputs)
  74. log.info("===============> load tensorflow model success <===============")
  75. def inference(self, image):
  76. data = {"data_name": image['data_name']}
  77. # 获得用户输入的图片
  78. log.info("===============> start load " + image['data_name'] + " <===============")
  79. # 推理所需的输入,目前的分类预置模型都只有一个输入
  80. input_dict = {}
  81. input_keys = self.signature_input_keys
  82. input_data = {}
  83. im = preprocess_input(self.load_image(image['data_path']), mode=self.args.prepare_mode)
  84. if len(list(im.shape)) == 3:
  85. input_data[input_keys[0]] = np.expand_dims(im, axis=0)
  86. for i in range(len(input_keys)):
  87. input_key = input_keys[i]
  88. input_tensor_name = self.signature_input_tensor_names[i]
  89. input_dict[input_tensor_name] = input_data[input_key]
  90. # 推理所需的输出tensor名
  91. output_tensor_names = self.signature_output_tensor_names
  92. # 进行推理,返回推理结果
  93. inference_result = self.session.run(output_tensor_names, feed_dict=input_dict)
  94. # 推理结果后处理
  95. data['predictions'] = list()
  96. for i in range(len(self.signature_output_keys)):
  97. output_key = self.signature_output_keys[i]
  98. if self.output_info_from_signature[output_key]['shape'][-1] >= 1000:
  99. # 返回Top 5 类
  100. top5 = np.argsort(inference_result[i][0])[::-1][0:5]
  101. for index in top5:
  102. if len(inference_result[i][0]) == 1001:
  103. result = {"label": clsidx_2_labels[index - 1], output_key: str(inference_result[i][0][index])}
  104. else:
  105. result = {"label": clsidx_2_labels[index], output_key: str(inference_result[i][0][index])}
  106. data['predictions'].append(result)
  107. return data
  108. def get_tensor_info_from_signature(data):
  109. tensor_info_dict = {}
  110. for name, tensor_info in data.items():
  111. tensor_shape = list(map(lambda dim: dim.size, tensor_info.tensor_shape.dim))
  112. tf_dtype = tf.dtypes.as_dtype(tensor_info.dtype)
  113. tensor_info_dict[name] = ({"shape": tensor_shape, "dtype": tf_dtype})
  114. return tensor_info_dict
  115. def get_tensors(data):
  116. keys = []
  117. tensor_names = []
  118. for name, tensor_info in data.items():
  119. keys.append(name)
  120. tensor_names.append(tensor_info.name)
  121. return keys, tensor_names

一站式算法开发平台、高性能分布式深度学习框架、先进算法模型库、视觉模型炼知平台、数据可视化分析平台等一系列平台及工具,在模型高效分布式训练、数据处理和可视分析、模型炼知和轻量化等技术上形成独特优势,目前已在产学研等各领域近千家单位及个人提供AI应用赋能

Contributors (1)