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.

pytorch_inference_service.py 3.6 kB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 os
  14. import io
  15. import torch
  16. import torch.nn.functional as functional
  17. from PIL import Image
  18. from torchvision import transforms
  19. import requests
  20. from imagenet1000_clsidx_to_labels import clsidx_2_labels
  21. from io import BytesIO
  22. from logger import Logger
  23. from service.abstract_inference_service import AbstractInferenceService
  24. log = Logger().logger
  25. class PytorchInferenceService(AbstractInferenceService):
  26. """
  27. pytorch 框架推理service
  28. """
  29. def __init__(self, args):
  30. super().__init__()
  31. self.args = args
  32. self.model_name = args.model_name
  33. self.model_path = args.model_path
  34. self.model = self.load_model()
  35. self.checkpoint = None
  36. def load_image(self, image_path):
  37. if image_path.startswith("http"):
  38. response = requests.get(image_path)
  39. response = response.content
  40. BytesIOObj = BytesIO()
  41. BytesIOObj.write(response)
  42. image = Image.open(BytesIOObj)
  43. else:
  44. image = open(image_path, 'rb').read()
  45. image = Image.open(io.BytesIO(image))
  46. if image.mode != 'RGB':
  47. image = image.convert("RGB")
  48. image = transforms.Resize((self.args.reshape_size[0], self.args.reshape_size[1]))(image)
  49. image = transforms.ToTensor()(image)
  50. image = transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])(image)
  51. image = image[None]
  52. if self.args.use_gpu:
  53. image = image.cuda()
  54. log.info("===============> load image success <===============")
  55. return image
  56. def load_model(self):
  57. log.info("===============> start load pytorch model :" + self.args.model_path + " <===============")
  58. if os.path.isfile(self.args.model_path):
  59. self.checkpoint = torch.load(self.model_path)
  60. else:
  61. for file in os.listdir(self.args.model_path):
  62. self.checkpoint = torch.load(self.model_path + file)
  63. model = self.checkpoint[self.args.model_structure]
  64. model.load_state_dict(self.checkpoint['state_dict'])
  65. for parameter in model.parameters():
  66. parameter.requires_grad = False
  67. if self.args.use_gpu:
  68. model.cuda()
  69. model.eval()
  70. log.info("===============> load pytorch model success <===============")
  71. return model
  72. def inference(self, image):
  73. data = {"data_name": image['data_name']}
  74. log.info("===============> start load " + image['data_name'] + " <===============")
  75. image = self.load_image(image['data_path'])
  76. preds = functional.softmax(self.model(image), dim=1)
  77. results = torch.topk(preds.data, k=5, dim=1)
  78. data['predictions'] = list()
  79. for prob, label in zip(results[0][0], results[1][0]):
  80. result = {"label": clsidx_2_labels[int(label)], "probability": "{:.3f}".format(float(prob))}
  81. data['predictions'].append(result)
  82. return data

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

Contributors (1)