object_detector_handler.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2022/2/28 11:29
  3. # @Author : MaochengHu
  4. # @Email : wojiaohumaocheng@gmail.com
  5. # @File : object_detector_handler.py
  6. # @Project : server_develop
  7. import os
  8. import sys
  9. import logging
  10. def import_env(names):
  11. for name in names:
  12. sys.path.append(os.path.join(os.getcwd(), name))
  13. names = ["src", "test", "config_files", "src/model_structure", "src/server_utils",
  14. "test", "test/test_src", "src/model_structure/yolov5_structure",
  15. "src/model_structure/yolov5_structure/yolov5-master",
  16. "src/model_structure/yolov5_structure/yolov5-master/utils/"]
  17. import_env(names)
  18. from server_utils.method_parser import parse
  19. from server_utils.recorder import Timer, logger
  20. from server_utils.image_convert import base642tensor
  21. from basic_model_handler import BasicModelHandler
  22. from model_structure.yolov5_structure.yolov5 import YOLOV5
  23. class ObjectDetectionHandler(BasicModelHandler):
  24. def __init__(self):
  25. super(ObjectDetectionHandler, self).__init__()
  26. self.yolov5_model = YOLOV5().create()
  27. @Timer.time_recorder
  28. def preprocess(self, data, cuda=True):
  29. body_data = data.get("body", None)
  30. assert body_data is not None, "get body(request info) is None"
  31. input_data = body_data.get("data")
  32. assert body_data is not None, "get data(request info) is None"
  33. output_methods = body_data.get("output_methods", [])
  34. input_source = base642tensor(input_data)
  35. logger.debug(f"input data is {input_data}, shape is {image.size}")
  36. logger.info("step 1: Preprocess successfully")
  37. return input_source, output_methods
  38. @Timer.time_recorder
  39. def postprocess(self, data, output_methods):
  40. result = parse(data, output_methods)
  41. return result
  42. @Timer.time_recorder
  43. def inference(self, data):
  44. result = self.yolov5_model(data)
  45. logger.info("step 2: Inference successfully")
  46. return result
  47. @Timer.time_recorder
  48. def handle(self, data: dict, context):
  49. """Entry point for default handler. It takes the data from the input request and returns
  50. the predicted outcome for the input.
  51. Args:
  52. data (dict): The input data that needs to be made a prediction request on.
  53. context (Context): It is a JSON Object containing information pertaining to
  54. the model artefacts parameters.
  55. Returns:
  56. list : Returns a list of dictionary with the predicted response.
  57. """
  58. self.context = context
  59. input_source, output_methods = self.preprocess(data)
  60. prediction = self.inference(input_source)
  61. output = self.postprocess(prediction, output_methods)
  62. return output