predictor.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  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. from typing import Any, Union, Dict, List, Tuple
  15. from ....utils.func_register import FuncRegister
  16. from ....modules.video_classification.model_list import MODELS
  17. from ...common.batch_sampler import VideoBatchSampler
  18. from ...common.reader import ReadVideo
  19. from ..common import (
  20. StaticInfer,
  21. )
  22. from ..base import BasicPredictor
  23. from .processors import (
  24. Scale,
  25. CenterCrop,
  26. Image2Array,
  27. NormalizeVideo,
  28. VideoClasTopk,
  29. ToBatch,
  30. )
  31. from .result import TopkVideoResult
  32. class VideoClasPredictor(BasicPredictor):
  33. entities = MODELS
  34. _FUNC_MAP = {}
  35. register = FuncRegister(_FUNC_MAP)
  36. def __init__(self, topk: Union[int, None] = None, *args, **kwargs):
  37. super().__init__(*args, **kwargs)
  38. self.topk = topk
  39. self.pre_tfs, self.infer, self.post_op = self._build()
  40. def _build_batch_sampler(self):
  41. return VideoBatchSampler()
  42. def _get_result_class(self):
  43. return TopkVideoResult
  44. def _build(self):
  45. pre_tfs = {}
  46. for cfg in self.config["PreProcess"]["transform_ops"]:
  47. tf_key = list(cfg.keys())[0]
  48. assert tf_key in self._FUNC_MAP
  49. func = self._FUNC_MAP[tf_key]
  50. args = cfg.get(tf_key, {})
  51. name, op = func(self, **args) if args else func(self)
  52. if op:
  53. pre_tfs[name] = op
  54. pre_tfs["ToBatch"] = ToBatch()
  55. infer = StaticInfer(
  56. model_dir=self.model_dir,
  57. model_prefix=self.MODEL_FILE_PREFIX,
  58. option=self.pp_option,
  59. )
  60. post_op = {}
  61. for key in self.config["PostProcess"]:
  62. func = self._FUNC_MAP.get(key)
  63. args = self.config["PostProcess"].get(key, {})
  64. name, op = func(self, **args) if args else func(self)
  65. post_op[name] = op
  66. return pre_tfs, infer, post_op
  67. def process(self, batch_data, topk: Union[int, None] = None):
  68. batch_raw_videos = self.pre_tfs["ReadVideo"](videos=batch_data)
  69. batch_videos = self.pre_tfs["Scale"](videos=batch_raw_videos)
  70. batch_videos = self.pre_tfs["CenterCrop"](videos=batch_videos)
  71. batch_videos = self.pre_tfs["Image2Array"](videos=batch_videos)
  72. batch_videos = self.pre_tfs["NormalizeVideo"](videos=batch_videos)
  73. x = self.pre_tfs["ToBatch"](videos=batch_videos)
  74. batch_preds = self.infer(x=x)
  75. batch_class_ids, batch_scores, batch_label_names = self.post_op["Topk"](
  76. batch_preds, topk=topk or self.topk
  77. )
  78. return {
  79. "input_path": batch_data,
  80. "class_ids": batch_class_ids,
  81. "scores": batch_scores,
  82. "label_names": batch_label_names,
  83. }
  84. @register("ReadVideo")
  85. def build_readvideo(
  86. self,
  87. num_seg=8,
  88. target_size=224,
  89. seg_len=1,
  90. sample_type=None,
  91. ):
  92. return "ReadVideo", ReadVideo(
  93. backend="decord",
  94. num_seg=num_seg,
  95. seg_len=seg_len,
  96. sample_type=sample_type,
  97. )
  98. @register("Scale")
  99. def build_scale(self, short_size=224):
  100. return "Scale", Scale(
  101. short_size=short_size,
  102. fixed_ratio=True,
  103. keep_ratio=None,
  104. do_round=False,
  105. )
  106. @register("CenterCrop")
  107. def build_center_crop(self, target_size=224):
  108. return "CenterCrop", CenterCrop(target_size=target_size)
  109. @register("Image2Array")
  110. def build_image2array(self, data_format="tchw"):
  111. return "Image2Array", Image2Array(transpose=True, data_format="tchw")
  112. @register("NormalizeVideo")
  113. def build_normalize(
  114. self,
  115. mean=[0.485, 0.456, 0.406],
  116. std=[0.229, 0.224, 0.225],
  117. ):
  118. return "NormalizeVideo", NormalizeVideo(mean=mean, std=std)
  119. @register("Topk")
  120. def build_topk(self, topk, label_list=None):
  121. if not self.topk:
  122. self.topk = int(topk)
  123. return "Topk", VideoClasTopk(class_ids=label_list)
  124. @register("KeepKeys")
  125. def foo(self, *args, **kwargs):
  126. return None, None