pipeline.py 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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, Dict, List, Optional, Union
  15. import numpy as np
  16. from ....utils.deps import pipeline_requires_extra
  17. from ...models.image_classification.result import TopkResult
  18. from ...utils.benchmark import benchmark
  19. from ...utils.hpi import HPIConfig
  20. from ...utils.pp_option import PaddlePredictorOption
  21. from .._parallel import AutoParallelImageSimpleInferencePipeline
  22. from ..base import BasePipeline
  23. @benchmark.time_methods
  24. class _ImageClassificationPipeline(BasePipeline):
  25. """Image Classification Pipeline"""
  26. def __init__(
  27. self,
  28. config: Dict,
  29. device: str = None,
  30. pp_option: PaddlePredictorOption = None,
  31. use_hpip: bool = False,
  32. hpi_config: Optional[Union[Dict[str, Any], HPIConfig]] = None,
  33. ) -> None:
  34. """
  35. Initializes the class with given configurations and options.
  36. Args:
  37. config (Dict): Configuration dictionary containing model and other parameters.
  38. device (str): The device to run the prediction on. Default is None.
  39. pp_option (PaddlePredictorOption): Options for PaddlePaddle predictor. Default is None.
  40. use_hpip (bool, optional): Whether to use the high-performance
  41. inference plugin (HPIP) by default. Defaults to False.
  42. hpi_config (Optional[Union[Dict[str, Any], HPIConfig]], optional):
  43. The default high-performance inference configuration dictionary.
  44. Defaults to None.
  45. """
  46. super().__init__(
  47. device=device, pp_option=pp_option, use_hpip=use_hpip, hpi_config=hpi_config
  48. )
  49. image_classification_model_config = config["SubModules"]["ImageClassification"]
  50. model_kwargs = {}
  51. if (topk := image_classification_model_config.get("topk", None)) is not None:
  52. model_kwargs = {"topk": topk}
  53. self.image_classification_model = self.create_model(
  54. image_classification_model_config, **model_kwargs
  55. )
  56. self.topk = image_classification_model_config.get("topk", 5)
  57. def predict(
  58. self, input: Union[str, List[str], np.ndarray, List[np.ndarray]], **kwargs
  59. ) -> TopkResult:
  60. """Predicts image classification results for the given input.
  61. Args:
  62. input (Union[str, list[str], np.ndarray, list[np.ndarray]]): The input image(s) or path(s) to the images.
  63. **kwargs: Additional keyword arguments that can be passed to the function.
  64. Returns:
  65. TopkResult: The predicted top k results.
  66. """
  67. topk = kwargs.pop("topk", self.topk)
  68. yield from self.image_classification_model(input, topk=topk)
  69. @pipeline_requires_extra("cv")
  70. class ImageClassificationPipeline(AutoParallelImageSimpleInferencePipeline):
  71. entities = "image_classification"
  72. @property
  73. def _pipeline_cls(self):
  74. return _ImageClassificationPipeline
  75. def _get_batch_size(self, config):
  76. return config["SubModules"]["ImageClassification"].get("batch_size", 1)