predictor.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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 lazy_paddle as paddle
  15. from ....utils.func_register import FuncRegister
  16. from ...common.batch_sampler import AudioBatchSampler
  17. from ..base import BasicPredictor
  18. from .result import WhisperResult
  19. from ...utils.io import AudioReader
  20. from .processors import (
  21. ModelDimensions,
  22. log_mel_spectrogram,
  23. Whisper,
  24. LANGUAGES,
  25. TO_LANGUAGE_CODE,
  26. )
  27. from ....modules.multilingual_speech_recognition.model_list import MODELS
  28. from ....utils.download import download_and_extract
  29. class WhisperPredictor(BasicPredictor):
  30. entities = MODELS
  31. def __init__(self, *args, **kwargs):
  32. """Initializes WhisperPredictor.
  33. Args:
  34. *args: Arbitrary positional arguments passed to the superclass.
  35. **kwargs: Arbitrary keyword arguments passed to the superclass.
  36. """
  37. super().__init__(*args, **kwargs)
  38. self.audio_reader = self._build()
  39. download_and_extract(
  40. self.config["resource_path"], self.config["resource_dir"], "assets"
  41. )
  42. def _build_batch_sampler(self):
  43. """Builds and returns an AudioBatchSampler instance.
  44. Returns:
  45. AudioBatchSampler: An instance of AudioBatchSampler.
  46. """
  47. return AudioBatchSampler()
  48. def _get_result_class(self):
  49. """Returns the result class, WhisperResult.
  50. Returns:
  51. type: The WhisperResult class.
  52. """
  53. return WhisperResult
  54. def _build(self):
  55. """Build the model, audio reader based on the configuration.
  56. Returns:
  57. AudioReader: An instance of AudioReader.
  58. """
  59. # build model
  60. model_dict = paddle.load(self.config["model_file"])
  61. dims = ModelDimensions(**model_dict["dims"])
  62. self.model = Whisper(dims)
  63. self.model.load_dict(model_dict)
  64. self.model.eval()
  65. # build audio reader
  66. audio_reader = AudioReader(backend="wav")
  67. return audio_reader
  68. def process(self, batch_data):
  69. """
  70. Process a batch of data through the preprocessing, inference, and postprocessing.
  71. Args:
  72. batch_data (List[Union[str, np.ndarray], ...]): A batch of input data (e.g., audio file paths).
  73. Returns:
  74. dict: A dictionary containing the input path and result. The result include 'text', 'segments' and 'language'.
  75. """
  76. # load mel_filters from resource_dir and extract feature for audio
  77. audio, sample_rate = self.audio_reader.read(batch_data[0])
  78. audio = paddle.to_tensor(audio)
  79. audio = audio[:, 0]
  80. audio = log_mel_spectrogram(audio, resource_path=self.config["resource_dir"])
  81. # model inference
  82. result = self.model.transcribe(
  83. audio,
  84. verbose=self.config["verbose"],
  85. task=self.config["task"],
  86. language=self.config["language"],
  87. resource_path=self.config["resource_dir"],
  88. temperature=self.config["temperature"],
  89. compression_ratio_threshold=self.config["compression_ratio_threshold"],
  90. logprob_threshold=self.config["logprob_threshold"],
  91. best_of=self.config["best_of"],
  92. beam_size=self.config["beam_size"],
  93. patience=self.config["patience"],
  94. length_penalty=self.config["length_penalty"],
  95. initial_prompt=self.config["initial_prompt"],
  96. condition_on_previous_text=self.config["condition_on_previous_text"],
  97. no_speech_threshold=self.config["no_speech_threshold"],
  98. )
  99. return {
  100. "input_path": batch_data,
  101. "result": [result],
  102. }