predictor.py 4.7 KB

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