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.
flashctc/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ # Copyright 2021-present Kensho Technologies, LLC.
2
+ from .alphabet import Alphabet
3
+ from .decoder import BeamSearchDecoderCTC, build_ctcdecoder
4
+ from .language_model import LanguageModel
5
+
6
+ __all__ = ["Alphabet", "BeamSearchDecoderCTC", "LanguageModel", "build_ctcdecoder"]
flashctc/alphabet.py ADDED
@@ -0,0 +1,176 @@
1
+ # Copyright 2021-present Kensho Technologies, LLC.
2
+ from __future__ import division
3
+
4
+ import json
5
+ import logging
6
+ import re
7
+ from typing import Collection, List
8
+
9
+ BPE_TOKEN = "▁" # nosec # representation of token boundary in BPE alphabet
10
+ UNK_TOKEN = "⁇" # nosec # representation of special UNK token in regular alphabet
11
+ UNK_BPE_TOKEN = "▁⁇▁" # nosec # representation of special UNK token in BPE alphabet
12
+
13
+ # special tokens are usually encode with things like `[]` or `<>`
14
+ SPECIAL_TOKEN_PTN = re.compile(r"^[<\[].+[>\]]$")
15
+ BLANK_TOKEN_PTN = re.compile(r"^[<\[]pad[>\]]$", flags=re.IGNORECASE)
16
+ UNK_TOKEN_PTN = re.compile(r"^[<\[]unk[>\]]$", flags=re.IGNORECASE)
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ def _check_if_bpe(labels: List[str]) -> bool:
22
+ """Check if input alphabet is BPE or not."""
23
+ is_bpe = any(s.startswith("##") for s in labels) or any(s.startswith(BPE_TOKEN) for s in labels)
24
+ if is_bpe:
25
+ logger.info("Alphabet determined to be of BPE style.")
26
+ else:
27
+ logger.info("Alphabet determined to be of regular style.")
28
+ return is_bpe
29
+
30
+
31
+ def _normalize_regular_alphabet(labels: List[str]) -> List[str]:
32
+ """Normalize non-bpe labels to alphabet for decoder."""
33
+ normalized_labels = labels[:]
34
+ # substitute space characters
35
+ if "|" in normalized_labels and " " not in normalized_labels:
36
+ logger.info("Found '|' in vocabulary but not ' ', doing substitution.")
37
+ normalized_labels[normalized_labels.index("|")] = " "
38
+ # substituted ctc blank char
39
+ for n, label in enumerate(normalized_labels):
40
+ if BLANK_TOKEN_PTN.match(label):
41
+ logger.info(
42
+ "Found %s in vocabulary, interpreted as a CTC blank token, substituting with %s.",
43
+ label,
44
+ "",
45
+ )
46
+ normalized_labels[n] = ""
47
+ if "_" in normalized_labels and "" not in normalized_labels:
48
+ logger.info("Found '_' in vocabulary but not '', doing substitution.")
49
+ normalized_labels[normalized_labels.index("_")] = ""
50
+ if "" not in normalized_labels:
51
+ logger.info("CTC blank char '' not found, appending to end.")
52
+ normalized_labels.append("")
53
+ # substitute unk
54
+ for n, label in enumerate(normalized_labels):
55
+ if UNK_TOKEN_PTN.match(label):
56
+ logger.info(
57
+ "Found %s in vocabulary, interpreting as unknown token, substituting with %s.",
58
+ label,
59
+ UNK_TOKEN,
60
+ )
61
+ normalized_labels[n] = UNK_TOKEN
62
+ # additional checks
63
+ if any(len(c) > 1 for c in normalized_labels):
64
+ logger.warning(
65
+ "Found entries of length > 1 in alphabet. This is unusual unless style is BPE, but the "
66
+ "alphabet was not recognized as BPE type. Is this correct?"
67
+ )
68
+ if " " not in normalized_labels:
69
+ logger.warning("Space token ' ' missing from vocabulary.")
70
+ return normalized_labels
71
+
72
+
73
+ def _convert_bpe_token_style(token: str) -> str:
74
+ """Convert token from ## style bpe format to ▁ style."""
75
+ if token.startswith("##"):
76
+ return token[2:]
77
+ elif SPECIAL_TOKEN_PTN.match(token) or token in ("", "<unk>", BPE_TOKEN, UNK_BPE_TOKEN):
78
+ return token
79
+ else:
80
+ return BPE_TOKEN + token
81
+
82
+
83
+ def _normalize_bpe_alphabet(labels: List[str]) -> List[str]:
84
+ """Normalize alphabet for bpe decoder."""
85
+ normalized_labels = labels[:]
86
+ # if BPE is of style '##' then convert it
87
+ if any(s.startswith("##") for s in labels):
88
+ normalized_labels = [_convert_bpe_token_style(c) for c in normalized_labels]
89
+ # substituted ctc blank char
90
+ for n, label in enumerate(normalized_labels):
91
+ if BLANK_TOKEN_PTN.match(label):
92
+ logger.info("Found %s in vocabulary, substituting with %s.", label, "")
93
+ normalized_labels[n] = ""
94
+ if "" not in normalized_labels:
95
+ logger.info("CTC blank char '' not found, appending to end.")
96
+ normalized_labels.append("")
97
+ # substitute unk
98
+ for n, label in enumerate(normalized_labels):
99
+ if UNK_TOKEN_PTN.match(label):
100
+ logger.info("Found %s in vocabulary, substituting with %s.", label, UNK_BPE_TOKEN)
101
+ normalized_labels[n] = UNK_BPE_TOKEN
102
+ # additional checks
103
+ if UNK_BPE_TOKEN not in normalized_labels:
104
+ logger.warning("UNK token %s not found, is this a mistake?", UNK_BPE_TOKEN)
105
+ return normalized_labels
106
+
107
+
108
+ def _verify_alphabet(labels: List[str], is_bpe: bool) -> None:
109
+ """Verify basic alphabet labels."""
110
+ # check if duplicates exist
111
+ if len(labels) != len(set(labels)):
112
+ raise ValueError("Alphabet contains duplicate entries, this is not allowed.")
113
+ # check if space character is absent in bpe alphabet
114
+ if is_bpe and any(" " in s for s in labels):
115
+ raise ValueError("Space token ' ' found in vocabulary even though it looks like BPE.")
116
+
117
+
118
+ class Alphabet:
119
+ def __init__(self, labels: List[str], is_bpe: bool) -> None:
120
+ """Init."""
121
+ self._labels = labels
122
+ self._is_bpe = is_bpe
123
+
124
+ @property
125
+ def is_bpe(self) -> bool:
126
+ """Whether the alphabet is bpe style."""
127
+ return self._is_bpe
128
+
129
+ @property
130
+ def labels(self) -> List[str]:
131
+ """Deep copy of the labels."""
132
+ return self._labels[:] # this is a copy
133
+
134
+ @classmethod
135
+ def build_alphabet(cls, labels: List[str]) -> "Alphabet":
136
+ """Make an alphabet from labels in standardized format for decoder."""
137
+ is_bpe = _check_if_bpe(labels)
138
+ _verify_alphabet(labels, is_bpe)
139
+ if is_bpe:
140
+ normalized_labels = _normalize_bpe_alphabet(labels)
141
+ else:
142
+ normalized_labels = _normalize_regular_alphabet(labels)
143
+ # different spellings of the blank or unknown token, like "" and "<pad>", become the same
144
+ duplicates = sorted(
145
+ {label for label in normalized_labels if normalized_labels.count(label) > 1}
146
+ )
147
+ if duplicates:
148
+ raise ValueError(
149
+ f"Alphabet entries {duplicates} appear more than once after normalization: "
150
+ "several labels stand for the same special token, this is not allowed."
151
+ )
152
+ return cls(normalized_labels, is_bpe)
153
+
154
+ def dumps(self) -> str:
155
+ """Dump an alphabet to a string."""
156
+ return json.dumps({"labels": self.labels, "is_bpe": self.is_bpe})
157
+
158
+ @classmethod
159
+ def loads(cls, s: str) -> "Alphabet":
160
+ """Load an alphabet from a string."""
161
+ as_dict = json.loads(s)
162
+ expected_keys = {"is_bpe", "labels"}
163
+ found_keys = set(as_dict.keys())
164
+ if set(found_keys) != expected_keys:
165
+ raise ValueError(f"unexpected keys found. Expected {expected_keys}, found {found_keys}")
166
+ return cls(as_dict["labels"], as_dict["is_bpe"])
167
+
168
+
169
+ def verify_alphabet_coverage(alphabet: Alphabet, unigrams: Collection[str]) -> None:
170
+ """Verify if alphabet covers a given unigrams."""
171
+ label_chars = set(alphabet.labels)
172
+ unigram_sample_chars = set("".join(unigrams))
173
+ if not unigram_sample_chars:
174
+ return
175
+ if len(unigram_sample_chars - label_chars) / len(unigram_sample_chars) > 0.2:
176
+ logger.warning("Unigrams and labels don't seem to agree.")
flashctc/constants.py ADDED
@@ -0,0 +1,18 @@
1
+ # Copyright 2021-present Kensho Technologies, LLC.
2
+ import math
3
+
4
+ # default parameters for decoding (can be modified)
5
+ DEFAULT_ALPHA = 0.5
6
+ DEFAULT_BETA = 1.5
7
+ DEFAULT_UNK_LOGP_OFFSET = -10.0
8
+ DEFAULT_BEAM_WIDTH = 100
9
+ DEFAULT_HOTWORD_WEIGHT = 10.0
10
+ DEFAULT_PRUNE_LOGP = -10.0
11
+ DEFAULT_PRUNE_BEAMS = False
12
+ DEFAULT_MIN_TOKEN_LOGP = -5.0
13
+ DEFAULT_SCORE_LM_BOUNDARY = True
14
+
15
+ # other constants for decoding
16
+ AVG_TOKEN_LEN = 6 # average number of characters expected per token (used for UNK scoring)
17
+ MIN_TOKEN_CLIP_P = 1e-15 # clipping to avoid underflow in case of malformed logit input
18
+ LOG_BASE_CHANGE_FACTOR = 1.0 / math.log10(math.e) # kenlm returns base10 but we like natural