Phu92kt commited on
Commit
10919b3
·
verified ·
1 Parent(s): 2c3da58

Create utils/tokenizer_base.py

Browse files
Files changed (1) hide show
  1. utils/tokenizer_base.py +142 -0
utils/tokenizer_base.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:
11
+ """Transforms labels according to the target charset."""
12
+
13
+ def __init__(self, target_charset) -> None:
14
+ super().__init__()
15
+ self.charset = target_charset
16
+ self.lowercase_only = target_charset == target_charset.lower()
17
+ self.uppercase_only = target_charset == target_charset.upper()
18
+
19
+ def __call__(self, label):
20
+ if self.lowercase_only:
21
+ label = label.lower()
22
+ elif self.uppercase_only:
23
+ label = label.upper()
24
+ return label
25
+
26
+
27
+ class BaseTokenizer(ABC):
28
+
29
+ def __init__(
30
+ self, charset: str, specials_first: tuple = (), specials_last: tuple = ()
31
+ ) -> None:
32
+ self._itos = specials_first + tuple(charset + "[UNK]") + specials_last
33
+ self._stoi = {s: i for i, s in enumerate(self._itos)}
34
+
35
+ def __len__(self):
36
+ return len(self._itos)
37
+
38
+ def _tok2ids(self, tokens: str) -> List[int]:
39
+ return [self._stoi[s] for s in tokens]
40
+
41
+ def _ids2tok(self, token_ids: List[int], join: bool = True) -> str:
42
+ tokens = [self._itos[i] for i in token_ids]
43
+ return "".join(tokens) if join else tokens
44
+
45
+ @abstractmethod
46
+ def encode(
47
+ self, labels: List[str], device: Optional[torch.device] = None
48
+ ) -> Tensor:
49
+ """Encode a batch of labels to a representation suitable for the model.
50
+ Args:
51
+ labels: List of labels. Each can be of arbitrary length.
52
+ device: Create tensor on this device.
53
+ Returns:
54
+ Batched tensor representation padded to the max label length. Shape: N, L
55
+ """
56
+ raise NotImplementedError
57
+
58
+ @abstractmethod
59
+ def _filter(self, probs: Tensor, ids: Tensor) -> Tuple[Tensor, List[int]]:
60
+ """Internal method which performs the necessary filtering prior to decoding."""
61
+ raise NotImplementedError
62
+
63
+ def decode(
64
+ self, token_dists: Tensor, raw: bool = False
65
+ ) -> Tuple[List[str], List[Tensor]]:
66
+ """Decode a batch of token distributions.
67
+ Args:
68
+ token_dists: softmax probabilities over the token distribution. Shape: N, L, C
69
+ raw: return unprocessed labels (will return list of list of strings)
70
+ Returns:
71
+ list of string labels (arbitrary length) and
72
+ their corresponding sequence probabilities as a list of Tensors
73
+ """
74
+ batch_tokens = []
75
+ batch_probs = []
76
+ for dist in token_dists:
77
+ probs, ids = dist.max(-1)
78
+ if not raw:
79
+ probs, ids = self._filter(probs, ids)
80
+ tokens = self._ids2tok(ids, not raw)
81
+ batch_tokens.append(tokens)
82
+ batch_probs.append(probs)
83
+ return batch_tokens, batch_probs
84
+
85
+
86
+ class Tokenizer(BaseTokenizer):
87
+ BOS = "[B]"
88
+ EOS = "[E]"
89
+ PAD = "[P]"
90
+
91
+ def __init__(self, charset: str) -> None:
92
+ specials_first = (self.EOS,)
93
+ specials_last = (self.BOS, self.PAD)
94
+ super().__init__(charset, specials_first, specials_last)
95
+ self.eos_id, self.bos_id, self.pad_id = [
96
+ self._stoi[s] for s in specials_first + specials_last
97
+ ]
98
+
99
+ def encode(
100
+ self, labels: List[str], device: Optional[torch.device] = None
101
+ ) -> Tensor:
102
+ batch = [
103
+ torch.as_tensor(
104
+ [self.bos_id] + self._tok2ids(y) + [self.eos_id],
105
+ dtype=torch.long,
106
+ device=device,
107
+ )
108
+ for y in labels
109
+ ]
110
+ return pad_sequence(batch, batch_first=True, padding_value=self.pad_id)
111
+
112
+ def _filter(self, probs: Tensor, ids: Tensor) -> Tuple[Tensor, List[int]]:
113
+ ids = ids.tolist()
114
+ try:
115
+ eos_idx = ids.index(self.eos_id)
116
+ except ValueError:
117
+ eos_idx = len(ids)
118
+ ids = ids[:eos_idx]
119
+ probs = probs[: eos_idx + 1]
120
+ return probs, ids
121
+
122
+
123
+ class CTCTokenizer(BaseTokenizer):
124
+ BLANK = "[B]"
125
+
126
+ def __init__(self, charset: str) -> None:
127
+ super().__init__(charset, specials_first=(self.BLANK,))
128
+ self.blank_id = self._stoi[self.BLANK]
129
+
130
+ def encode(
131
+ self, labels: List[str], device: Optional[torch.device] = None
132
+ ) -> Tensor:
133
+ batch = [
134
+ torch.as_tensor(self._tok2ids(y), dtype=torch.long, device=device)
135
+ for y in labels
136
+ ]
137
+ return pad_sequence(batch, batch_first=True, padding_value=self.blank_id)
138
+
139
+ def _filter(self, probs: Tensor, ids: Tensor) -> Tuple[Tensor, List[int]]:
140
+ ids = list(zip(*groupby(ids.tolist())))[0]
141
+ ids = [x for x in ids if x != self.blank_id]
142
+ return probs, ids