pipeline.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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.open_vocabulary_segmentation.results import SAMSegResult
  18. from ...utils.hpi import HPIConfig
  19. from ...utils.pp_option import PaddlePredictorOption
  20. from ..base import BasePipeline
  21. Number = Union[int, float]
  22. @pipeline_requires_extra("multimodal")
  23. class OpenVocabularySegmentationPipeline(BasePipeline):
  24. """Open Vocabulary Segmentation pipeline"""
  25. entities = "open_vocabulary_segmentation"
  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. # create box-prompted SAM-H
  50. box_prompted_model_cfg = config.get("SubModules", {}).get(
  51. "BoxPromptSegmentation",
  52. {"model_config_error": "config error for doc_ori_classify_model!"},
  53. )
  54. self.box_prompted_model = self.create_model(box_prompted_model_cfg)
  55. # create point-prompted SAM-H
  56. point_prompted_model_cfg = config.get("SubModules", {}).get(
  57. "PointPromptSegmentation",
  58. {"model_config_error": "config error for doc_ori_classify_model!"},
  59. )
  60. self.point_prompted_model = self.create_model(point_prompted_model_cfg)
  61. def predict(
  62. self,
  63. input: Union[str, List[str], np.ndarray, List[np.ndarray]],
  64. prompt: Union[List[List[float]], np.ndarray],
  65. prompt_type: str = "box",
  66. **kwargs
  67. ) -> SAMSegResult:
  68. """Predicts image segmentation results for the given input.
  69. Args:
  70. input (str | list[str] | np.ndarray | list[np.ndarray]): The input image(s) or path(s) to the images.
  71. prompt (list[list[float]] | np.ndarray): The prompt for the input image(s).
  72. prompt_type (str): The type of prompt, either 'box' or 'point'. Default is 'box'.
  73. **kwargs: Additional keyword arguments that can be passed to the function.
  74. Returns:
  75. SAMSegResult: The predicted SAM segmentation results.
  76. """
  77. if prompt_type == "box":
  78. yield from self.box_prompted_model(input, prompts={"box_prompt": prompt})
  79. elif prompt_type == "point":
  80. yield from self.point_prompted_model(
  81. input, prompts={"point_prompt": prompt}
  82. )
  83. else:
  84. raise ValueError(
  85. "Invalid prompt type. Only 'box' and 'point' are supported"
  86. )