whispering/whisper_streaming/transcriber.py

302 lines
11 KiB
Python
Raw Normal View History

2022-09-23 10:20:11 +00:00
#!/usr/bin/env python3
2022-09-23 13:13:25 +00:00
from logging import getLogger
2022-09-23 11:41:44 +00:00
from typing import Iterator, List, Optional, Union
2022-09-23 10:20:11 +00:00
import numpy as np
import torch
from whisper import Whisper, load_model
2022-09-23 11:03:00 +00:00
from whisper.audio import (
HOP_LENGTH,
N_FRAMES,
SAMPLE_RATE,
log_mel_spectrogram,
pad_or_trim,
)
2022-09-23 10:20:11 +00:00
from whisper.decoding import DecodingOptions, DecodingResult
from whisper.tokenizer import get_tokenizer
2022-09-23 11:03:00 +00:00
from whisper.utils import exact_div
2022-09-23 10:20:11 +00:00
2022-09-23 11:03:00 +00:00
from whisper_streaming.schema import ParsedChunk, WhisperConfig
2022-09-23 10:20:11 +00:00
2022-09-23 13:01:40 +00:00
logger = getLogger(__name__)
2022-09-23 10:20:11 +00:00
class WhisperStreamingTranscriber:
2022-09-23 13:39:27 +00:00
def _set_dtype(self, fp16: bool):
self.fp16 = fp16
self.dtype = torch.float16 if fp16 else torch.float32
if self.model.device == torch.device("cpu"):
if torch.cuda.is_available():
logger.warning("Performing inference on CPU when CUDA is available")
if self.dtype == torch.float16:
logger.warning("FP16 is not supported on CPU; using FP32 instead")
self.dtype = torch.float32
if self.dtype == torch.float32:
self.fp16 = False
2022-09-23 10:20:11 +00:00
def __init__(self, *, config: WhisperConfig):
self.config: WhisperConfig = config
self.model: Whisper = load_model(config.model_name, device=config.device)
self.tokenizer = get_tokenizer(
self.model.is_multilingual,
language=config.language,
task="transcribe",
)
2022-09-23 13:39:27 +00:00
self._set_dtype(config.fp16)
2022-09-23 11:03:00 +00:00
self.timestamp: float = 0.0
self.input_stride = exact_div(
N_FRAMES, self.model.dims.n_audio_ctx
) # mel frames per output token: 2
self.time_precision = (
self.input_stride * HOP_LENGTH / SAMPLE_RATE
) # time per output token: 0.02 (seconds)
self.buffer_tokens = []
2022-09-23 12:50:26 +00:00
self.buffer_mel = None
2022-09-23 10:20:11 +00:00
def _get_decoding_options(
self,
*,
t,
2022-09-23 12:25:05 +00:00
prompt,
2022-09-23 10:20:11 +00:00
beam_size: Optional[int],
patience: float,
best_of: Optional[int],
) -> DecodingOptions:
return DecodingOptions(
task="transcribe",
2022-09-24 00:42:10 +00:00
language=self.config.language,
2022-09-23 10:20:11 +00:00
temperature=t,
sample_len=None,
best_of=best_of,
beam_size=beam_size,
patience=patience,
length_penalty=None,
2022-09-23 12:25:05 +00:00
prompt=prompt,
2022-09-23 10:20:11 +00:00
prefix=None,
suppress_blank=True,
suppress_tokens="-1",
without_timestamps=False,
max_initial_timestamp=0.0,
2022-09-23 13:39:27 +00:00
fp16=self.fp16,
2022-09-23 10:20:11 +00:00
)
2022-09-23 12:25:05 +00:00
def _decode_with_fallback(
self,
*,
segment: np.ndarray,
) -> List[DecodingResult]:
2022-09-23 10:20:11 +00:00
assert len(self.config.temperatures) >= 1
t = self.config.temperatures[0]
2022-09-24 01:09:16 +00:00
logger.debug(f"temperature: {t}")
2022-09-23 10:20:11 +00:00
_decode_options1: DecodingOptions = self._get_decoding_options(
t=t,
2022-09-23 12:25:05 +00:00
prompt=self.buffer_tokens,
2022-09-23 10:20:11 +00:00
beam_size=self.config.beam_size,
patience=0.0,
best_of=None,
)
results: List[DecodingResult] = self.model.decode(segment, _decode_options1) # type: ignore
for t in self.config.temperatures[1:]:
needs_fallback = [
self.config.compression_ratio_threshold is not None
and result.compression_ratio > self.config.compression_ratio_threshold
or self.config.logprob_threshold is not None
and result.avg_logprob < self.config.logprob_threshold
for result in results
]
if any(needs_fallback):
2022-09-24 04:06:22 +00:00
logger.debug(
f"Fall back with temperature: {t}, needs_fallback: {needs_fallback}"
)
2022-09-23 10:20:11 +00:00
_decode_options2: DecodingOptions = self._get_decoding_options(
t=t,
2022-09-23 12:25:05 +00:00
prompt=self.buffer_tokens,
2022-09-23 10:20:11 +00:00
beam_size=None,
patience=0.0,
best_of=self.config.best_of,
)
retries: List[DecodingResult] = self.model.decode(
segment[needs_fallback], _decode_options2 # type: ignore
)
for retry_index, original_index in enumerate(
np.nonzero(needs_fallback)[0]
):
results[original_index] = retries[retry_index]
2022-09-24 04:06:22 +00:00
else:
break
2022-09-24 01:09:16 +00:00
logger.debug(f"# of results: {len(results)}")
2022-09-23 10:20:11 +00:00
return results
2022-09-23 11:03:00 +00:00
def _get_chunk(
self,
*,
start: float,
end: float,
text_tokens: torch.Tensor,
result: DecodingResult,
) -> Optional[ParsedChunk]:
text = self.tokenizer.decode(
[token for token in text_tokens if token < self.tokenizer.eot] # type: ignore
)
if len(text.strip()) == 0: # skip empty text output
return
return ParsedChunk(
start=start,
end=end,
text=text,
tokens=result.tokens,
temperature=result.temperature,
avg_logprob=result.avg_logprob,
compression_ratio=result.compression_ratio,
no_speech_prob=result.no_speech_prob,
)
2022-09-23 11:41:44 +00:00
def _deal_timestamp(
self, *, result, segment_duration
) -> Iterator[Union[ParsedChunk, int]]:
2022-09-23 11:03:00 +00:00
tokens = torch.tensor(result.tokens)
timestamp_tokens: torch.Tensor = tokens.ge(self.tokenizer.timestamp_begin)
consecutive = torch.where(timestamp_tokens[:-1] & timestamp_tokens[1:])[0].add_(
1
)
if (
len(consecutive) > 0
): # if the output contains two consecutive timestamp tokens
2022-09-23 13:31:26 +00:00
logger.debug(f"Length of consecutive: {len(consecutive)}")
2022-09-23 11:03:00 +00:00
last_slice = 0
for current_slice in consecutive:
sliced_tokens = tokens[last_slice:current_slice]
2022-09-24 15:28:05 +00:00
logger.debug(f" last_slice={last_slice}, current_slice={current_slice}")
2022-09-23 11:03:00 +00:00
start_timestamp_position = (
sliced_tokens[0].item() - self.tokenizer.timestamp_begin
)
end_timestamp_position = (
sliced_tokens[-1].item() - self.tokenizer.timestamp_begin
)
chunk = self._get_chunk(
start=self.timestamp
+ start_timestamp_position * self.time_precision,
end=self.timestamp + end_timestamp_position * self.time_precision,
text_tokens=sliced_tokens[1:-1],
result=result,
)
if chunk is not None:
yield chunk
last_slice = current_slice
2022-09-23 11:41:44 +00:00
last_timestamp_position0: int = (
tokens[last_slice - 1].item()
- self.tokenizer.timestamp_begin # type:ignore
2022-09-23 11:03:00 +00:00
)
self.buffer_tokens.extend(tokens[: last_slice + 1].tolist())
2022-09-23 11:41:44 +00:00
self.timestamp += last_timestamp_position0 * self.time_precision
yield last_timestamp_position0
2022-09-23 11:03:00 +00:00
else:
duration = segment_duration
timestamps = tokens[timestamp_tokens.nonzero().flatten()]
2022-09-24 05:22:33 +00:00
logger.debug(f"Length of consecutive: 0, timestamps: {timestamps}")
2022-09-23 11:03:00 +00:00
if len(timestamps) > 0:
# no consecutive timestamps but it has a timestamp; use the last one.
# single timestamp at the end means no speech after the last timestamp.
last_timestamp_position = (
timestamps[-1].item() - self.tokenizer.timestamp_begin
)
duration = last_timestamp_position * self.time_precision
2022-09-24 05:22:33 +00:00
logger.debug(f"segment_duration: {segment_duration}, Duration: {duration}")
2022-09-23 11:03:00 +00:00
chunk = self._get_chunk(
start=self.timestamp,
end=self.timestamp + duration,
text_tokens=tokens,
result=result,
)
if chunk is not None:
yield chunk
2022-09-23 13:11:36 +00:00
self.timestamp += duration
2022-09-23 11:03:00 +00:00
if result.temperature > 0.5:
# do not feed the prompt tokens if a high temperature was used
del self.buffer_tokens
self.buffer_tokens = []
2022-09-23 14:07:01 +00:00
logger.debug(f"Length of buffer: {len(self.buffer_tokens)}")
2022-09-23 11:03:00 +00:00
2022-09-23 10:20:11 +00:00
def transcribe(
self,
*,
segment: np.ndarray,
2022-09-23 11:03:00 +00:00
) -> Iterator[ParsedChunk]:
2022-09-23 12:50:26 +00:00
new_mel = log_mel_spectrogram(audio=segment).unsqueeze(0)
2022-09-24 15:28:05 +00:00
logger.debug(f"Incoming new_mel.shape: {new_mel.shape}")
2022-09-23 12:50:26 +00:00
if self.buffer_mel is None:
mel = new_mel
else:
2022-09-24 16:01:29 +00:00
logger.debug(f"buffer_mel.shape: {self.buffer_mel.shape}")
2022-09-23 12:50:26 +00:00
mel = torch.cat([self.buffer_mel, new_mel], dim=-1)
self.buffer_mel = None
2022-09-24 15:28:05 +00:00
logger.debug(f"mel.shape: {mel.shape}")
2022-09-23 12:50:26 +00:00
seek: int = 0
while seek < mel.shape[-1]:
segment = (
pad_or_trim(mel[:, :, seek:], N_FRAMES)
.to(self.model.device) # type: ignore
.to(self.dtype)
)
2022-09-24 15:43:03 +00:00
if not self.config.allow_padding and segment.shape[-1] > mel.shape[-1]:
2022-09-24 06:39:41 +00:00
logger.warning("Padding is not expected while speaking")
2022-09-23 12:50:26 +00:00
2022-09-24 06:27:02 +00:00
logger.debug(
2022-09-24 15:28:05 +00:00
f"seek={seek}, timestamp={self.timestamp}, "
2022-09-24 06:27:02 +00:00
f"mel.shape: {mel.shape}, segment.shape: {segment.shape}"
)
2022-09-23 12:50:26 +00:00
results = self._decode_with_fallback(
segment=segment,
)
result = results[0]
2022-09-23 14:07:01 +00:00
logger.debug(
2022-09-23 14:28:25 +00:00
f"Result: temperature={result.temperature:.2f}, no_speech_prob={result.no_speech_prob:.2f}, "
f"avg_logprob={result.avg_logprob:.2f}"
2022-09-23 14:07:01 +00:00
)
2022-09-23 10:20:11 +00:00
2022-09-23 12:50:26 +00:00
if self.config.no_speech_threshold is not None:
if (result.no_speech_prob > self.config.no_speech_threshold) and not (
self.config.logprob_threshold is not None
and result.avg_logprob > self.config.logprob_threshold
):
2022-09-23 13:26:22 +00:00
seek += segment.shape[-1]
2022-09-24 06:27:02 +00:00
logger.debug(
f"Skip: {segment.shape[-1]}, new seek={seek}, mel.shape: {mel.shape}"
)
2022-09-23 13:26:22 +00:00
continue
2022-09-23 12:50:26 +00:00
segment_duration = segment.shape[-1] * HOP_LENGTH / SAMPLE_RATE
last_timestamp_position: Optional[int] = None
for v in self._deal_timestamp(
result=result, segment_duration=segment_duration
2022-09-23 10:20:11 +00:00
):
2022-09-23 12:50:26 +00:00
if isinstance(v, int):
last_timestamp_position = v
else:
yield v
if last_timestamp_position is None:
seek += segment.shape[-1]
2022-09-23 11:41:44 +00:00
else:
2022-09-24 05:22:33 +00:00
seek += last_timestamp_position * self.input_stride
2022-09-24 06:27:02 +00:00
logger.debug(f"new seek={seek}, mel.shape: {mel.shape}")
2022-09-23 12:50:26 +00:00
2022-09-24 15:43:03 +00:00
if (not self.config.allow_padding) and (mel.shape[-1] - seek < N_FRAMES):
2022-09-24 06:39:41 +00:00
break
2022-09-23 12:50:26 +00:00
2022-09-24 15:28:05 +00:00
if mel.shape[-1] - seek <= 0:
logger.debug(f"self.buffer_mel is None ({mel.shape}, {seek})")
2022-09-24 06:39:41 +00:00
return
self.buffer_mel = mel[:, :, seek:]
2022-09-24 15:28:05 +00:00
logger.debug(f"self.buffer_mel.shape: {self.buffer_mel.shape}")
2022-09-23 12:50:26 +00:00
del mel