Update utils/tokenizer_base.py
Browse files- utils/tokenizer_base.py +25 -37
utils/tokenizer_base.py
CHANGED
|
@@ -1,10 +1,7 @@
|
|
| 1 |
from abc import ABC, abstractmethod
|
| 2 |
from itertools import groupby
|
| 3 |
from typing import List, Optional, Tuple
|
| 4 |
-
|
| 5 |
-
import torch
|
| 6 |
-
from torch import Tensor
|
| 7 |
-
from torch.nn.utils.rnn import pad_sequence
|
| 8 |
|
| 9 |
|
| 10 |
class CharsetAdapter:
|
|
@@ -38,18 +35,20 @@ class BaseTokenizer(ABC):
|
|
| 38 |
return "".join(tokens) if join else tokens
|
| 39 |
|
| 40 |
@abstractmethod
|
| 41 |
-
def encode(self, labels: List[str], device
|
| 42 |
raise NotImplementedError
|
| 43 |
|
| 44 |
@abstractmethod
|
| 45 |
-
def _filter(self, probs:
|
| 46 |
raise NotImplementedError
|
| 47 |
|
| 48 |
-
def decode(self, token_dists:
|
| 49 |
batch_tokens = []
|
| 50 |
-
batch_probs
|
| 51 |
for dist in token_dists:
|
| 52 |
-
|
|
|
|
|
|
|
| 53 |
if not raw:
|
| 54 |
probs, ids = self._filter(probs, ids)
|
| 55 |
tokens = self._ids2tok(ids, not raw)
|
|
@@ -65,32 +64,25 @@ class Tokenizer(BaseTokenizer):
|
|
| 65 |
|
| 66 |
def __init__(self, charset: str) -> None:
|
| 67 |
specials_first = (self.EOS,)
|
| 68 |
-
specials_last
|
| 69 |
super().__init__(charset, specials_first, specials_last)
|
| 70 |
self.eos_id, self.bos_id, self.pad_id = [
|
| 71 |
self._stoi[s] for s in specials_first + specials_last
|
| 72 |
]
|
| 73 |
|
| 74 |
-
def encode(self, labels: List[str], device
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
[self.bos_id] + self._tok2ids(y) + [self.eos_id],
|
| 78 |
-
dtype=torch.long,
|
| 79 |
-
device=device,
|
| 80 |
-
)
|
| 81 |
-
for y in labels
|
| 82 |
-
]
|
| 83 |
-
return pad_sequence(batch, batch_first=True, padding_value=self.pad_id)
|
| 84 |
|
| 85 |
-
def _filter(self, probs:
|
| 86 |
-
|
| 87 |
try:
|
| 88 |
-
eos_idx =
|
| 89 |
except ValueError:
|
| 90 |
-
eos_idx = len(
|
| 91 |
-
|
| 92 |
-
probs
|
| 93 |
-
return probs,
|
| 94 |
|
| 95 |
|
| 96 |
class CTCTokenizer(BaseTokenizer):
|
|
@@ -100,14 +92,10 @@ class CTCTokenizer(BaseTokenizer):
|
|
| 100 |
super().__init__(charset, specials_first=(self.BLANK,))
|
| 101 |
self.blank_id = self._stoi[self.BLANK]
|
| 102 |
|
| 103 |
-
def encode(self, labels: List[str], device
|
| 104 |
-
|
| 105 |
-
torch.as_tensor(self._tok2ids(y), dtype=torch.long, device=device)
|
| 106 |
-
for y in labels
|
| 107 |
-
]
|
| 108 |
-
return pad_sequence(batch, batch_first=True, padding_value=self.blank_id)
|
| 109 |
|
| 110 |
-
def _filter(self, probs:
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
return probs,
|
|
|
|
| 1 |
from abc import ABC, abstractmethod
|
| 2 |
from itertools import groupby
|
| 3 |
from typing import List, Optional, Tuple
|
| 4 |
+
import numpy as np
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
class CharsetAdapter:
|
|
|
|
| 35 |
return "".join(tokens) if join else tokens
|
| 36 |
|
| 37 |
@abstractmethod
|
| 38 |
+
def encode(self, labels: List[str], device=None):
|
| 39 |
raise NotImplementedError
|
| 40 |
|
| 41 |
@abstractmethod
|
| 42 |
+
def _filter(self, probs: np.ndarray, ids: np.ndarray) -> Tuple[np.ndarray, List[int]]:
|
| 43 |
raise NotImplementedError
|
| 44 |
|
| 45 |
+
def decode(self, token_dists: np.ndarray, raw: bool = False) -> Tuple[List[str], List[np.ndarray]]:
|
| 46 |
batch_tokens = []
|
| 47 |
+
batch_probs = []
|
| 48 |
for dist in token_dists:
|
| 49 |
+
# numpy argmax replaces torch dist.max(-1) — no dispatcher, no autograd
|
| 50 |
+
ids = np.argmax(dist, axis=-1)
|
| 51 |
+
probs = dist[np.arange(len(ids)), ids] # gather max probs
|
| 52 |
if not raw:
|
| 53 |
probs, ids = self._filter(probs, ids)
|
| 54 |
tokens = self._ids2tok(ids, not raw)
|
|
|
|
| 64 |
|
| 65 |
def __init__(self, charset: str) -> None:
|
| 66 |
specials_first = (self.EOS,)
|
| 67 |
+
specials_last = (self.BOS, self.PAD)
|
| 68 |
super().__init__(charset, specials_first, specials_last)
|
| 69 |
self.eos_id, self.bos_id, self.pad_id = [
|
| 70 |
self._stoi[s] for s in specials_first + specials_last
|
| 71 |
]
|
| 72 |
|
| 73 |
+
def encode(self, labels: List[str], device=None):
|
| 74 |
+
# encode() is not used during inference — kept for completeness
|
| 75 |
+
raise NotImplementedError("encode() not needed for inference")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
def _filter(self, probs: np.ndarray, ids: np.ndarray) -> Tuple[np.ndarray, List[int]]:
|
| 78 |
+
ids_list = ids.tolist()
|
| 79 |
try:
|
| 80 |
+
eos_idx = ids_list.index(self.eos_id)
|
| 81 |
except ValueError:
|
| 82 |
+
eos_idx = len(ids_list)
|
| 83 |
+
ids_list = ids_list[:eos_idx]
|
| 84 |
+
probs = probs[:eos_idx + 1]
|
| 85 |
+
return probs, ids_list
|
| 86 |
|
| 87 |
|
| 88 |
class CTCTokenizer(BaseTokenizer):
|
|
|
|
| 92 |
super().__init__(charset, specials_first=(self.BLANK,))
|
| 93 |
self.blank_id = self._stoi[self.BLANK]
|
| 94 |
|
| 95 |
+
def encode(self, labels: List[str], device=None):
|
| 96 |
+
raise NotImplementedError("encode() not needed for inference")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
+
def _filter(self, probs: np.ndarray, ids: np.ndarray) -> Tuple[np.ndarray, List[int]]:
|
| 99 |
+
ids_list = list(zip(*groupby(ids.tolist())))[0]
|
| 100 |
+
ids_list = [x for x in ids_list if x != self.blank_id]
|
| 101 |
+
return probs, ids_list
|