Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add hotwords feature #2070

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions whisper/decoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ class DecodingOptions:

# implementation details
fp16: bool = True # use fp16 for most of the calculation
hotwords: Optional[str] = None


@dataclass(frozen=True)
Expand Down Expand Up @@ -598,15 +599,20 @@ def _get_initial_tokens(self) -> Tuple[int]:
prefix_tokens = prefix_tokens[-max_prefix_len:]
tokens = tokens + prefix_tokens

if prompt := self.options.prompt:
if (prompt := self.options.prompt) or ((self.options.hotwords) and not self.options.prefix):
prompt_tokens = (
self.tokenizer.encode(" " + prompt.strip())
if isinstance(prompt, str)
else prompt
)
if (hotwords := self.options.hotwords) and not self.options.prefix:
hotwords_tokens = self.tokenizer.encode(" " + hotwords.strip())
if len(hotwords_tokens) >= self.n_ctx // 2:
hotwords_tokens = hotwords_tokens[: self.n_ctx // 2 - 1]
tokens = (
[self.tokenizer.sot_prev]
+ prompt_tokens[-(self.n_ctx // 2 - 1) :]
+ (hotwords_tokens if self.options.hotwords is not None else [])
+ (prompt_tokens[-(self.n_ctx // 2 - 1) :] if self.options.prompt is not None else [])
+ tokens
)

Expand Down
7 changes: 7 additions & 0 deletions whisper/transcribe.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def transcribe(
append_punctuations: str = "\"'.。,,!!??::”)]}、",
clip_timestamps: Union[str, List[float]] = "0",
hallucination_silence_threshold: Optional[float] = None,
hotwords: Optional[str] = None,
**decode_options,
):
"""
Expand Down Expand Up @@ -113,6 +114,9 @@ def transcribe(
When word_timestamps is True, skip silent periods longer than this threshold (in seconds)
when a possible hallucination is detected

hotwords: Optional[str]
optional hotwords to provide as a prompt for the all window.

Returns
-------
A dictionary containing the resulting text ("text") and segment-level details ("segments"), and
Expand Down Expand Up @@ -275,6 +279,7 @@ def new_segment(
segment_duration = segment_size * HOP_LENGTH / SAMPLE_RATE
mel_segment = pad_or_trim(mel_segment, N_FRAMES).to(model.device).to(dtype)

decode_options["hotwords"] = hotwords
decode_options["prompt"] = all_tokens[prompt_reset_since:]
result: DecodingResult = decode_with_fallback(mel_segment)
tokens = torch.tensor(result.tokens)
Expand Down Expand Up @@ -546,6 +551,8 @@ def valid_model_name(name):
parser.add_argument("--threads", type=optional_int, default=0, help="number of threads used by torch for CPU inference; supercedes MKL_NUM_THREADS/OMP_NUM_THREADS")
parser.add_argument("--clip_timestamps", type=str, default="0", help="comma-separated list start,end,start,end,... timestamps (in seconds) of clips to process, where the last end timestamp defaults to the end of the file")
parser.add_argument("--hallucination_silence_threshold", type=optional_float, help="(requires --word_timestamps True) skip silent periods longer than this threshold (in seconds) when a possible hallucination is detected")
parser.add_argument("--hotwords", type=str, default=None, help="optional hotwords to provide as a prompt for the all window")

# fmt: on

args = parser.parse_args().__dict__
Expand Down