flashctc 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,519 @@
1
+ # Copyright 2021-present Kensho Technologies, LLC.
2
+ from __future__ import division
3
+
4
+ import abc
5
+ import json
6
+ import logging
7
+ import os
8
+ import re
9
+ import shutil
10
+ from typing import Any, Collection, Dict, Iterable, Optional, Pattern, Sequence, Set, Tuple, cast
11
+
12
+ import numpy as np
13
+ from pygtrie import CharTrie # type: ignore
14
+
15
+ from .constants import (
16
+ AVG_TOKEN_LEN,
17
+ DEFAULT_ALPHA,
18
+ DEFAULT_BETA,
19
+ DEFAULT_HOTWORD_WEIGHT,
20
+ DEFAULT_SCORE_LM_BOUNDARY,
21
+ DEFAULT_UNK_LOGP_OFFSET,
22
+ LOG_BASE_CHANGE_FACTOR,
23
+ )
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+ try:
28
+ import kenlm # type: ignore
29
+ except ImportError:
30
+ logger.warning(
31
+ "kenlm python bindings are not installed, so language models are not available. "
32
+ "Install them with: pip install camel-kenlm"
33
+ )
34
+
35
+
36
+ class AbstractLMState(abc.ABC): # noqa: B024 # a base to extend, nothing is abstract
37
+ """Abstract container for state information."""
38
+
39
+ def get_mp_safe_state(self) -> Optional["AbstractLMState"]:
40
+ """Get a multiprocessing-safe version of the state if available."""
41
+ return None
42
+
43
+
44
+ class KenlmState(AbstractLMState):
45
+ def __init__(self, state: "kenlm.State") -> None:
46
+ """State for a kenlm language model."""
47
+ self._state = state
48
+
49
+ @property
50
+ def state(self) -> "kenlm.State":
51
+ """Get the raw state object."""
52
+ return self._state
53
+
54
+
55
+ class MultiLanguageModelState(AbstractLMState):
56
+ def __init__(self, states: Sequence[AbstractLMState]) -> None:
57
+ """State for a multilanguage model."""
58
+ self._states = states
59
+
60
+ @property
61
+ def states(self) -> Sequence[AbstractLMState]:
62
+ """Access the state objects."""
63
+ return self._states
64
+
65
+
66
+ def load_unigram_set_from_arpa(arpa_path: str) -> Set[str]:
67
+ """Read unigrams from arpa file."""
68
+ unigrams = set()
69
+ with open(arpa_path) as f:
70
+ start_1_gram = False
71
+ for line in f:
72
+ line = line.strip()
73
+ if line == "\\1-grams:":
74
+ start_1_gram = True
75
+ elif line == "\\2-grams:":
76
+ break
77
+ if start_1_gram and len(line) > 0:
78
+ # "logprob<TAB>word[<TAB>backoff]": the backoff may be left out
79
+ parts = line.split("\t")
80
+ if len(parts) in (2, 3):
81
+ unigrams.add(parts[1])
82
+ if len(unigrams) == 0:
83
+ raise ValueError("No unigrams found in arpa file. Something is wrong with the file.")
84
+ return unigrams
85
+
86
+
87
+ def _prepare_unigram_set(unigrams: Collection[str], kenlm_model: "kenlm.Model") -> Set[str]:
88
+ """Filter unigrams down to vocabulary that exists in kenlm_model."""
89
+ if len(unigrams) < 1000:
90
+ logger.warning(
91
+ "Only %s unigrams passed as vocabulary. Is this small or artificial data?",
92
+ len(unigrams),
93
+ )
94
+ unigram_set = set(unigrams)
95
+ unigram_set = {t for t in unigram_set if t in kenlm_model}
96
+ retained_fraction = 1.0 if len(unigrams) == 0 else len(unigram_set) / len(unigrams)
97
+ if retained_fraction < 0.1:
98
+ logger.warning(
99
+ "Only %s%% of unigrams in vocabulary found in kenlm model-- this might mean that your "
100
+ "vocabulary and language model are incompatible. Is this intentional?",
101
+ round(retained_fraction * 100, 1),
102
+ )
103
+ return unigram_set
104
+
105
+
106
+ def _get_empty_lm_state() -> "kenlm.State":
107
+ """Get unintialized kenlm state."""
108
+ try:
109
+ kenlm_state = kenlm.State()
110
+ except ImportError as err:
111
+ raise ValueError("To use a language model, you need to install kenlm.") from err
112
+ return kenlm_state
113
+
114
+
115
+ class HotwordScorer:
116
+ def __init__(
117
+ self,
118
+ match_ptn: Pattern[str],
119
+ char_trie: CharTrie,
120
+ weight: float = DEFAULT_HOTWORD_WEIGHT,
121
+ ) -> None:
122
+ """Scorer for hotwords if provided.
123
+
124
+ Args:
125
+ match_ptn: match pattern for hotword unigrams
126
+ char_trie: trie for all hotwords to do partial matching
127
+ weight: weight for score increase
128
+ """
129
+ self._match_ptn = match_ptn
130
+ self._char_trie = char_trie
131
+ self._weight = weight
132
+ # set by build_scorer when there are no hotwords, so callers can skip scoring
133
+ self._is_empty = False
134
+
135
+ @property
136
+ def is_empty(self) -> bool:
137
+ """Whether the scorer has no hotwords, so every score is zero."""
138
+ return self._is_empty
139
+
140
+ def __contains__(self, item: str) -> bool:
141
+ """Contains."""
142
+ return cast(bool, self._char_trie.has_node(item) > 0)
143
+
144
+ def score(self, text: str) -> float:
145
+ """Get total hotword score for input text."""
146
+ return self._weight * len(self._match_ptn.findall(text))
147
+
148
+ def score_partial_token(self, token: str) -> float:
149
+ """Get total hotword score for input text."""
150
+ if token in self:
151
+ # find shortest unigram starting with the given partial token
152
+ min_len = len(next(self._char_trie.iterkeys(token, shallow=True)))
153
+ # scale score by length of unigram matched so far
154
+ score = self._weight * len(token) / min_len
155
+ else:
156
+ score = 0.0
157
+ return score
158
+
159
+ @classmethod
160
+ def build_scorer(
161
+ cls, hotwords: Optional[Iterable[str]] = None, weight: float = DEFAULT_HOTWORD_WEIGHT
162
+ ) -> "HotwordScorer":
163
+ """Use hotword list to create regex pattern and character trie for scoring."""
164
+ # make sure we get an iterable
165
+ hotwords = hotwords or []
166
+ # remove whitespace
167
+ hotwords = [s.strip() for s in hotwords if len(s.strip()) > 0]
168
+ if len(hotwords) > 0:
169
+ hotword_unigrams = []
170
+ for ngram in hotwords:
171
+ # split ngrams to get words
172
+ for unigram in ngram.split():
173
+ hotword_unigrams.append(unigram)
174
+
175
+ # create pattern to match full words
176
+ # sort by length to get longest possible match
177
+ # use lookahead and lookbehind to match on word boundary instead of '\b' to only match
178
+ # on space or bos/eos
179
+ match_ptn = re.compile(
180
+ r"|".join(
181
+ [
182
+ r"(?<!\S)" + re.escape(s) + r"(?!\S)"
183
+ for s in sorted(hotword_unigrams, key=len, reverse=True)
184
+ ]
185
+ )
186
+ )
187
+
188
+ # create trie for partial word matches
189
+ length_sorted_unigrams = sorted(hotword_unigrams, key=len)
190
+ char_trie = CharTrie.fromkeys(length_sorted_unigrams)
191
+ else:
192
+ # make an unmatchable pattern
193
+ match_ptn = re.compile(r"^\b$")
194
+ # empty trie
195
+ char_trie = CharTrie()
196
+ scorer = cls(match_ptn, char_trie, weight)
197
+ scorer._is_empty = len(hotwords) == 0
198
+ return scorer
199
+
200
+
201
+ class AbstractLanguageModel(abc.ABC):
202
+ @property
203
+ @abc.abstractmethod
204
+ def order(self) -> int:
205
+ """Get the order of the n-gram language model."""
206
+ raise NotImplementedError()
207
+
208
+ @abc.abstractmethod
209
+ def get_start_state(self) -> AbstractLMState:
210
+ """Get initial lm state."""
211
+ raise NotImplementedError()
212
+
213
+ @abc.abstractmethod
214
+ def score_partial_token(self, partial_token: str) -> float:
215
+ """Get partial token score."""
216
+ raise NotImplementedError()
217
+
218
+ @abc.abstractmethod
219
+ def score(
220
+ self, prev_state: AbstractLMState, word: str, is_last_word: bool = False
221
+ ) -> Tuple[float, AbstractLMState]:
222
+ """Score word conditional on previous lm state.
223
+
224
+ At the end of decoding the decoder calls this with ``is_last_word=True`` and
225
+ ``word=""`` when the last word has already been scored (the utterance ended on a word
226
+ boundary, or produced no words). That call should return only the end of sentence score.
227
+ """
228
+ raise NotImplementedError()
229
+
230
+ def save_to_dir(self, filepath: str) -> None:
231
+ """Save model to a directory."""
232
+ # this is deliberately not abstract
233
+ raise NotImplementedError()
234
+
235
+ @classmethod
236
+ def load_from_dir(cls, filepath: str) -> "AbstractLanguageModel":
237
+ """Load a model from a directory."""
238
+ raise NotImplementedError()
239
+
240
+ def reset_params(self, **params: Dict[str, Any]) -> None: # noqa: B027 # optional to override
241
+ """Reset some of the parameters in place."""
242
+
243
+
244
+ class LanguageModel(AbstractLanguageModel):
245
+ # serializatoin constants
246
+ # json attrs will get serialized into a single json file
247
+ JSON_ATTRS = ("alpha", "beta", "unk_score_offset", "score_boundary")
248
+ _ATTRS_SERIALIZED_FILENAME = "attrs.json"
249
+ _UNIGRAMS_SERIALIZED_FILENAME = "unigrams.txt"
250
+
251
+ def __init__(
252
+ self,
253
+ kenlm_model: "kenlm.Model",
254
+ unigrams: Optional[Collection[str]] = None,
255
+ alpha: float = DEFAULT_ALPHA,
256
+ beta: float = DEFAULT_BETA,
257
+ unk_score_offset: float = DEFAULT_UNK_LOGP_OFFSET,
258
+ score_boundary: bool = DEFAULT_SCORE_LM_BOUNDARY,
259
+ ) -> None:
260
+ """Language model container class to consolidate functionality.
261
+
262
+ Args:
263
+ kenlm_model: instance of kenlm n-gram language model `kenlm.Model`
264
+ unigrams: list of known word unigrams
265
+ alpha: weight for language model during shallow fusion
266
+ beta: weight for length score adjustment of during scoring
267
+ unk_score_offset: amount of log score offset for unknown tokens
268
+ score_boundary: whether to have kenlm respect boundaries when scoring
269
+ """
270
+ self._kenlm_model = kenlm_model
271
+ if unigrams is None:
272
+ logger.warning("No known unigrams provided, decoding results might be a lot worse.")
273
+ unigram_set = set()
274
+ char_trie = None
275
+ else:
276
+ unigram_set = _prepare_unigram_set(unigrams, self._kenlm_model)
277
+ char_trie = CharTrie.fromkeys(unigram_set)
278
+ self._unigram_set = unigram_set
279
+ self._char_trie = char_trie
280
+ self.alpha = alpha
281
+ self.beta = beta
282
+ self.unk_score_offset = unk_score_offset
283
+ self.score_boundary = score_boundary
284
+
285
+ def reset_params(self, **params: Dict[str, Any]) -> None:
286
+ """Reset some of the simple parameters.
287
+
288
+ The allowed parameters are [alpha, beta, unk_score_offset, score_boundary]
289
+
290
+ Args:
291
+ params: dict of str to anything
292
+ """
293
+ alpha = params.get("alpha")
294
+ if alpha is not None:
295
+ if isinstance(alpha, bool) or not isinstance(alpha, (int, float)):
296
+ raise ValueError(f"alpha must be a float. Got {type(alpha)}.")
297
+ self.alpha = float(alpha)
298
+
299
+ beta = params.get("beta")
300
+ if beta is not None:
301
+ if isinstance(beta, bool) or not isinstance(beta, (int, float)):
302
+ raise ValueError(f"beta must be a float. Got {type(beta)}.")
303
+ self.beta = float(beta)
304
+
305
+ unk_score_offset = params.get("unk_score_offset")
306
+ if unk_score_offset is not None:
307
+ if isinstance(unk_score_offset, bool) or not isinstance(unk_score_offset, (int, float)):
308
+ raise ValueError(f"unk_score_offset must be a float. Got {type(unk_score_offset)}.")
309
+ self.unk_score_offset = float(unk_score_offset)
310
+
311
+ score_boundary = params.get("score_boundary")
312
+ if score_boundary is not None:
313
+ if not isinstance(score_boundary, bool):
314
+ raise ValueError(f"score_boundary must be a bool. Got {type(score_boundary)}.")
315
+ self.score_boundary = score_boundary
316
+
317
+ @property
318
+ def order(self) -> int:
319
+ """Get the order of the n-gram language model."""
320
+ return cast(int, self._kenlm_model.order)
321
+
322
+ def get_start_state(self) -> KenlmState:
323
+ """Get initial lm state."""
324
+ start_state = _get_empty_lm_state()
325
+ if self.score_boundary:
326
+ self._kenlm_model.BeginSentenceWrite(start_state)
327
+ else:
328
+ self._kenlm_model.NullContextWrite(start_state)
329
+ return KenlmState(start_state)
330
+
331
+ def _get_raw_end_score(self, start_state: "kenlm.State") -> float:
332
+ """Calculate final lm score."""
333
+ if self.score_boundary:
334
+ end_state = _get_empty_lm_state()
335
+ score: float = self._kenlm_model.BaseScore(start_state, "</s>", end_state)
336
+ else:
337
+ score = 0.0
338
+ return score
339
+
340
+ def score_partial_token(self, partial_token: str) -> float:
341
+ """Get partial token score."""
342
+ if self._char_trie is None:
343
+ is_oov = 1.0
344
+ else:
345
+ is_oov = int(self._char_trie.has_node(partial_token) == 0)
346
+ unk_score = self.unk_score_offset * is_oov
347
+ # if unk token length exceeds expected length then additionally decrease score
348
+ if len(partial_token) > AVG_TOKEN_LEN:
349
+ unk_score = unk_score * len(partial_token) / AVG_TOKEN_LEN
350
+ return unk_score
351
+
352
+ def score(
353
+ self, prev_state: AbstractLMState, word: str, is_last_word: bool = False
354
+ ) -> Tuple[float, KenlmState]:
355
+ """Score word conditional on start state."""
356
+ if not isinstance(prev_state, KenlmState):
357
+ raise AssertionError(
358
+ f"Wrong input state type found. Expected KenlmState, got {type(prev_state)}"
359
+ )
360
+ if is_last_word and word == "":
361
+ # The utterance ended on a word boundary, so the last word was already scored.
362
+ # Only the end of sentence term is left; "" must not be scored as an unknown word.
363
+ lm_score = self._get_raw_end_score(prev_state.state)
364
+ return self.alpha * lm_score * LOG_BASE_CHANGE_FACTOR, prev_state
365
+ end_state = _get_empty_lm_state()
366
+ lm_score = self._kenlm_model.BaseScore(prev_state.state, word, end_state)
367
+ # override UNK prob. use unigram set if we have because it's faster
368
+ if (
369
+ len(self._unigram_set) > 0 and word not in self._unigram_set
370
+ ) or word not in self._kenlm_model:
371
+ lm_score += self.unk_score_offset
372
+ # add end of sentence context if needed
373
+ if is_last_word:
374
+ # note that we want to return the unmodified end_state to keep extension capabilities
375
+ lm_score = lm_score + self._get_raw_end_score(end_state)
376
+ lm_score = self.alpha * lm_score * LOG_BASE_CHANGE_FACTOR + self.beta
377
+ return lm_score, KenlmState(end_state)
378
+
379
+ # Serialization stuff below
380
+ # Language models are annoying to serialize because the kenlm model MUST be an actual file
381
+ # and not just something that is file-like. Language models are written to a directory with
382
+ # three files:
383
+ # unigrams.txt: hold the unigrams. Empty (not non-existent) if there are no unigrams
384
+ # attrs.json: json serialized attributes for alpha, beta, etc
385
+ # kenlm file (.arpa, .bin, or .binary)
386
+ # No other files are allowed in the directory (hidden files are ignored)
387
+
388
+ @property
389
+ def serializable_attrs(self) -> Dict[str, Any]:
390
+ """Get a dictionary of the attributes to serialize to json."""
391
+ json_attrs = {}
392
+ for attr in LanguageModel.JSON_ATTRS:
393
+ val = getattr(self, attr)
394
+ if val is None:
395
+ raise ValueError(f"attribute {attr} not found. Cannot serialize")
396
+ json_attrs[attr] = val
397
+ return json_attrs
398
+
399
+ def save_to_dir(self, filepath: str, unigram_encoding: Optional[str] = None) -> None:
400
+ """Save to a directory."""
401
+ json_attrs = self.serializable_attrs
402
+ json_attr_path = os.path.join(filepath, self._ATTRS_SERIALIZED_FILENAME)
403
+ unigrams_path = os.path.join(filepath, self._UNIGRAMS_SERIALIZED_FILENAME)
404
+ kenlm_filename = os.path.split(self._kenlm_model.path.decode("utf-8"))[1]
405
+ kenlm_path = os.path.join(filepath, kenlm_filename)
406
+
407
+ with open(json_attr_path, "w") as fi:
408
+ json.dump(json_attrs, fi)
409
+
410
+ with open(unigrams_path, "w", encoding=unigram_encoding) as fi:
411
+ for unigram in sorted(self._unigram_set):
412
+ fi.write(unigram + "\n")
413
+
414
+ logger.info(
415
+ "copying kenlm model from %s to %s. This may take some time",
416
+ self._kenlm_model.path,
417
+ kenlm_path,
418
+ )
419
+ shutil.copy2(self._kenlm_model.path, kenlm_path)
420
+
421
+ @staticmethod
422
+ def parse_directory_contents(filepath: str) -> Dict[str, str]:
423
+ """Check the contents of a directory for the correct files."""
424
+ contents = os.listdir(filepath)
425
+ # filter out hidden files
426
+ contents = [c for c in contents if not c.startswith(".") and not c.startswith("__")]
427
+ if len(contents) != 3:
428
+ raise ValueError(
429
+ f"Found wrong number of files in directory. Expected 3 files, found {contents}"
430
+ )
431
+ if LanguageModel._ATTRS_SERIALIZED_FILENAME not in contents:
432
+ raise ValueError(f"did not find attributes file in files: {contents}")
433
+ else:
434
+ contents.remove(LanguageModel._ATTRS_SERIALIZED_FILENAME)
435
+ if LanguageModel._UNIGRAMS_SERIALIZED_FILENAME not in contents:
436
+ raise ValueError(f"did not find unigrams file in files: {contents}")
437
+ else:
438
+ contents.remove(LanguageModel._UNIGRAMS_SERIALIZED_FILENAME)
439
+ # now all that's left is the kenlm file, which can be ".arpa" or ".bin"
440
+ kenlm_file = contents[0]
441
+ if os.path.splitext(kenlm_file)[1] not in {".arpa", ".bin", ".binary"}:
442
+ raise ValueError(
443
+ f"Explected kenlm file to end in `.arpa` or `.bin(ary)`. Found {kenlm_file}"
444
+ )
445
+ return {
446
+ "json_attrs": os.path.join(filepath, LanguageModel._ATTRS_SERIALIZED_FILENAME),
447
+ "unigrams": os.path.join(filepath, LanguageModel._UNIGRAMS_SERIALIZED_FILENAME),
448
+ "kenlm": os.path.join(filepath, kenlm_file),
449
+ }
450
+
451
+ @classmethod
452
+ def load_from_dir(
453
+ cls, filepath: str, unigram_encoding: Optional[str] = None
454
+ ) -> "LanguageModel":
455
+ """Load from a directory."""
456
+ filenames = cls.parse_directory_contents(filepath)
457
+ with open(filenames["json_attrs"], "r") as fi:
458
+ json_attrs = json.load(fi)
459
+ if set(json_attrs.keys()) != set(cls.JSON_ATTRS):
460
+ raise ValueError(
461
+ f"Expected json serialized attributes to be {cls.JSON_ATTRS} "
462
+ f"but found {json_attrs.keys()}"
463
+ )
464
+
465
+ with open(filenames["unigrams"], "r", encoding=unigram_encoding) as fi:
466
+ unigrams = fi.read().splitlines()
467
+
468
+ kenlm_model = kenlm.Model(filenames["kenlm"])
469
+ return cls(kenlm_model, unigrams, **json_attrs)
470
+
471
+
472
+ class MultiLanguageModel(AbstractLanguageModel):
473
+ def __init__(self, language_models: Sequence[AbstractLanguageModel]) -> None:
474
+ """Container for multiple language models.
475
+
476
+ Args:
477
+ language_models: list of language models
478
+ """
479
+ if len(language_models) < 2:
480
+ raise ValueError("This class is meant to contain at least 2 language models.")
481
+ self._language_models = language_models
482
+
483
+ @property
484
+ def order(self) -> int:
485
+ """Get the maximum order of the contained n-gram language model."""
486
+ return max([lm.order for lm in self._language_models])
487
+
488
+ def get_start_state(self) -> MultiLanguageModelState:
489
+ """Get initial lm state."""
490
+ return MultiLanguageModelState([lm.get_start_state() for lm in self._language_models])
491
+
492
+ def score_partial_token(self, partial_token: str) -> float:
493
+ """Get partial token score."""
494
+ return float(
495
+ np.mean([lm.score_partial_token(partial_token) for lm in self._language_models])
496
+ )
497
+
498
+ def score(
499
+ self, prev_state: AbstractLMState, word: str, is_last_word: bool = False
500
+ ) -> Tuple[float, MultiLanguageModelState]:
501
+ """Score word conditional on previous lm state."""
502
+ if not isinstance(prev_state, MultiLanguageModelState):
503
+ raise AssertionError(
504
+ f"Wrong input state type found. Expected MultiLanguageModelState, got "
505
+ f"{type(prev_state)}"
506
+ )
507
+ if len(prev_state.states) != len(self._language_models):
508
+ raise AssertionError(
509
+ f"Number of states ({len(prev_state.states)}) does not match number of language "
510
+ f"models ({len(self._language_models)})."
511
+ )
512
+ score = 0.0
513
+ end_state = []
514
+ for lm_prev_state, lm in zip(prev_state.states, self._language_models, strict=True):
515
+ lm_score, lm_end_state = lm.score(lm_prev_state, word, is_last_word=is_last_word)
516
+ score += lm_score
517
+ end_state.append(lm_end_state)
518
+ score = score / len(self._language_models)
519
+ return score, MultiLanguageModelState(end_state)
flashctc/py.typed ADDED
File without changes