predictor.py 4.8 KB

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