File size: 9,313 Bytes
0d80816
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# Copyright      2020  Mobvoi Inc.        (authors: Fangjun Kuang)
#
# See ../../../LICENSE for clarification regarding multiple authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from dataclasses import dataclass
from dataclasses import field
from typing import Dict
from typing import Generic
from typing import List
from typing import Optional
from typing import TypeVar
from typing import Union

Symbol = TypeVar('Symbol')

# SymbolTable is copied from
# https://github.com/k2-fsa/k2/blob/master/k2/python/k2/symbol_table.py

'''
    SymbolTable: map symbol to id
'''
@dataclass(repr=False)
class SymbolTable(Generic[Symbol]):
    '''SymbolTable that maps symbol IDs, found on the FSA arcs to
    actual objects. These objects can be arbitrary Python objects
    that can serve as keys in a dictionary (i.e. they need to be
    hashable and immutable).

    The SymbolTable can only be read to/written from disk if the
    symbols are strings.
    '''
    _id2sym: Dict[int, Symbol] = field(default_factory=dict)
    '''Map an integer to a symbol.
    '''

    _sym2id: Dict[Symbol, int] = field(default_factory=dict)
    '''Map a symbol to an integer.
    '''

    _next_available_id: int = 1
    '''A helper internal field that helps adding new symbols
    to the table efficiently.
    '''

    eps: Symbol = '<eps>'
    '''Null symbol, always mapped to index 0.
    '''

    def __post_init__(self):
        assert all(self._sym2id[sym] == idx for idx, sym in self._id2sym.items())
        assert all(self._id2sym[idx] == sym for sym, idx in self._sym2id.items())
        assert 0 not in self._id2sym or self._id2sym[0] == self.eps

        self._next_available_id = max(self._id2sym, default=0) + 1
        self._id2sym.setdefault(0, self.eps)
        self._sym2id.setdefault(self.eps, 0)


    @staticmethod
    def from_str(s: str) -> 'SymbolTable':
        '''Build a symbol table from a string.

        The string consists of lines. Every line has two fields separated
        by space(s), tab(s) or both. The first field is the symbol and the
        second the integer id of the symbol.

        Args:
          s:
            The input string with the format described above.
        Returns:
          An instance of :class:`SymbolTable`.
        '''
        id2sym: Dict[int, str] = dict()
        sym2id: Dict[str, int] = dict()

        for line in s.split('\n'):
            fields = line.split()
            if len(fields) == 0:
                continue  # skip empty lines
            assert len(fields) == 2, \
                    f'Expect a line with 2 fields. Given: {len(fields)}'
            sym, idx = fields[0], int(fields[1])
            assert sym not in sym2id, f'Duplicated symbol {sym}'
            assert idx not in id2sym, f'Duplicated id {idx}'
            id2sym[idx] = sym
            sym2id[sym] = idx

        eps = id2sym.get(0, '<eps>')

        return SymbolTable(_id2sym=id2sym, _sym2id=sym2id, eps=eps)

    @staticmethod
    def from_file(filename: str) -> 'SymbolTable':
        '''Build a symbol table from file.

        Every line in the symbol table file has two fields separated by
        space(s), tab(s) or both. The following is an example file:

        .. code-block::

            <eps> 0
            a 1
            b 2
            c 3

        Args:
          filename:
            Name of the symbol table file. Its format is documented above.

        Returns:
          An instance of :class:`SymbolTable`.

        '''
        with open(filename, 'r', encoding='utf-8') as f:
            return SymbolTable.from_str(f.read().strip())

    def to_str(self) -> str:
        '''
        Returns:
          Return a string representation of this object. You can pass
          it to the method ``from_str`` to recreate an identical object.
        '''
        s = ''
        for idx, symbol in sorted(self._id2sym.items()):
            s += f'{symbol} {idx}\n'
        return s

    def to_file(self, filename: str):
        '''Serialize the SymbolTable to a file.

        Every line in the symbol table file has two fields separated by
        space(s), tab(s) or both. The following is an example file:

        .. code-block::

            <eps> 0
            a 1
            b 2
            c 3

        Args:
          filename:
            Name of the symbol table file. Its format is documented above.
        '''
        with open(filename, 'w') as f:
            for idx, symbol in sorted(self._id2sym.items()):
                print(symbol, idx, file=f)                

    def add(self, symbol: Symbol, index: Optional[int] = None) -> int:
        '''Add a new symbol to the SymbolTable.

        Args:
            symbol:
                The symbol to be added.
            index:
                Optional int id to which the symbol should be assigned.
                If it is not available, a ValueError will be raised.

        Returns:
            The int id to which the symbol has been assigned.
        '''
        # Already in the table? Return its ID.
        if symbol in self._sym2id:
            return self._sym2id[symbol]
        # Specific ID not provided - use next available.
        if index is None:
            index = self._next_available_id
        # Specific ID provided but not available.
        if index in self._id2sym:
            raise ValueError(f"Cannot assign id '{index}' to '{symbol}' - "
                             f"already occupied by {self._id2sym[index]}")
        self._sym2id[symbol] = index
        self._id2sym[index] = symbol

        # Update next available ID if needed
        if self._next_available_id <= index:
            self._next_available_id = index + 1

        return index

    def get(self, k: Union[int, Symbol]) -> Union[Symbol, int]:
        '''Get a symbol for an id or get an id for a symbol

        Args:
          k:
            If it is an id, it tries to find the symbol corresponding
            to the id; if it is a symbol, it tries to find the id
            corresponding to the symbol.

        Returns:
          An id or a symbol depending on the given `k`.
        '''
        if isinstance(k, int):
            return self._id2sym[k]
        else:
            return self._sym2id[k]

    def merge(self, other: 'SymbolTable') -> 'SymbolTable':
        '''Create a union of two SymbolTables.
        Raises an AssertionError if the same IDs are occupied by
        different symbols.

        Args:
            other:
                A symbol table to merge with ``self``.

        Returns:
            A new symbol table.
        '''
        self._check_compatible(other)
        return SymbolTable(
            _id2sym={**self._id2sym, **other._id2sym},
            _sym2id={**self._sym2id, **other._sym2id},
            eps=self.eps
        )
        
    def _check_compatible(self, other: 'SymbolTable') -> None:
        # Epsilon compatibility
        assert self.eps == other.eps, f'Mismatched epsilon symbol: ' \
                                      f'{self.eps} != {other.eps}'
        # IDs compatibility
        common_ids = set(self._id2sym).intersection(other._id2sym)
        for idx in common_ids:
            assert self[idx] == other[idx], f'ID conflict for id: {idx}, ' \
                                            f'self[idx] = "{self[idx]}", ' \
                                            f'other[idx] = "{other[idx]}"'
        # Symbols compatibility
        common_symbols = set(self._sym2id).intersection(other._sym2id)
        for sym in common_symbols:
            assert self[sym] == other[sym], f'ID conflict for id: {sym}, ' \
                                            f'self[sym] = "{self[sym]}", ' \
                                            f'other[sym] = "{other[sym]}"'

    def __getitem__(self, item: Union[int, Symbol]) -> Union[Symbol, int]:
        return self.get(item)

    def __contains__(self, item: Union[int, Symbol]) -> bool:
        if isinstance(item, int):
            return item in self._id2sym
        else:
            return item in self._sym2id

    def __len__(self) -> int:
        return len(self._id2sym)

    def __eq__(self, other: 'SymbolTable') -> bool:
        if len(self) != len(other):
            return False

        for s in self.symbols:
            if self[s] != other[s]:
                return False

        return True

    @property
    def ids(self) -> List[int]:
        '''Returns a list of integer IDs corresponding to the symbols.
        '''
        ans = list(self._id2sym.keys())
        ans.sort()
        return ans

    @property
    def symbols(self) -> List[Symbol]:
        '''Returns a list of symbols (e.g., strings) corresponding to
        the integer IDs.
        '''
        ans = list(self._sym2id.keys())
        ans.sort()
        return ans