predictor.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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(
  34. self.config["resource_path"], self.config["resource_dir"], "assets"
  35. )
  36. def _build_batch_sampler(self):
  37. """Builds and returns an AudioBatchSampler instance.
  38. Returns:
  39. AudioBatchSampler: An instance of AudioBatchSampler.
  40. """
  41. return AudioBatchSampler()
  42. def _get_result_class(self):
  43. """Returns the result class, WhisperResult.
  44. Returns:
  45. type: The WhisperResult class.
  46. """
  47. return WhisperResult
  48. def _build(self):
  49. """Build the model, audio reader based on the configuration.
  50. Returns:
  51. AudioReader: An instance of AudioReader.
  52. """
  53. from .processors import (
  54. ModelDimensions,
  55. Whisper,
  56. LANGUAGES,
  57. TO_LANGUAGE_CODE,
  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. from .processors import log_mel_spectrogram
  77. # load mel_filters from resource_dir and extract feature for audio
  78. audio, sample_rate = self.audio_reader.read(batch_data[0])
  79. audio = paddle.to_tensor(audio)
  80. audio = audio[:, 0]
  81. audio = log_mel_spectrogram(audio, resource_path=self.config["resource_dir"])
  82. # adapt temperature
  83. temperature_increment_on_fallback = self.config[
  84. "temperature_increment_on_fallback"
  85. ]
  86. if (
  87. temperature_increment_on_fallback is not None
  88. and temperature_increment_on_fallback != "None"
  89. ):
  90. temperature = tuple(
  91. np.arange(
  92. self.config["temperature"],
  93. 1.0 + 1e-6,
  94. temperature_increment_on_fallback,
  95. )
  96. )
  97. else:
  98. temperature = [self.config["temperature"]]
  99. # model inference
  100. result = self.model.transcribe(
  101. audio,
  102. verbose=self.config["verbose"],
  103. task=self.config["task"],
  104. language=self.config["language"],
  105. resource_path=self.config["resource_dir"],
  106. temperature=temperature,
  107. compression_ratio_threshold=self.config["compression_ratio_threshold"],
  108. logprob_threshold=self.config["logprob_threshold"],
  109. best_of=self.config["best_of"],
  110. beam_size=self.config["beam_size"],
  111. patience=self.config["patience"],
  112. length_penalty=self.config["length_penalty"],
  113. initial_prompt=self.config["initial_prompt"],
  114. condition_on_previous_text=self.config["condition_on_previous_text"],
  115. no_speech_threshold=self.config["no_speech_threshold"],
  116. )
  117. return {
  118. "input_path": batch_data,
  119. "result": [result],
  120. }