predictor.py 4.8 KB

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