predictor.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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 numpy as np
  16. from pathlib import Path
  17. from ...base import BasePredictor
  18. from ...base.predictor.transforms import image_common
  19. from .keys import ShiTuRecKeys as K
  20. from .utils import InnerConfig
  21. from ....utils import logging
  22. from . import transforms as T
  23. from ..model_list import MODELS
  24. class ShiTuRecPredictor(BasePredictor):
  25. """ShiTu Recognition Predictor"""
  26. entities = MODELS
  27. def load_other_src(self):
  28. """load the inner config file"""
  29. infer_cfg_file_path = os.path.join(self.model_dir, "inference.yml")
  30. if not os.path.exists(infer_cfg_file_path):
  31. raise FileNotFoundError(f"Cannot find config file: {infer_cfg_file_path}")
  32. return InnerConfig(infer_cfg_file_path)
  33. @classmethod
  34. def get_input_keys(cls):
  35. """get input keys"""
  36. return [[K.IMAGE], [K.IM_PATH]]
  37. @classmethod
  38. def get_output_keys(cls):
  39. """get output keys"""
  40. return [K.SHITU_REC_PRED]
  41. def _run(self, batch_input):
  42. """run"""
  43. input_dict = {}
  44. input_dict[K.IMAGE] = np.stack(
  45. [data[K.IMAGE] for data in batch_input], axis=0
  46. ).astype(dtype=np.float32, copy=False)
  47. input_ = [input_dict[K.IMAGE]]
  48. outputs = self._predictor.predict(input_)
  49. shitu_rec_outs = outputs[0]
  50. # In-place update
  51. pred = batch_input
  52. for dict_, shitu_rec_out in zip(pred, shitu_rec_outs):
  53. dict_[K.SHITU_REC_PRED] = shitu_rec_out
  54. return pred
  55. def _get_pre_transforms_from_config(self):
  56. """get preprocess transforms"""
  57. logging.info(
  58. f"Transformation operators for data preprocessing will be inferred from config file."
  59. )
  60. pre_transforms = self.other_src.pre_transforms
  61. pre_transforms.insert(0, image_common.ReadImage(format="RGB"))
  62. return pre_transforms
  63. def _get_post_transforms_from_config(self):
  64. """get postprocess transforms"""
  65. post_transforms = self.other_src.post_transforms
  66. if not self.disable_print:
  67. post_transforms.append(T.PrintShiTuRecResult())
  68. return post_transforms