Base class for converting from ints to/from human readable strings.
| 50 | |
| 51 | |
| 52 | class TextEncoder(object): |
| 53 | """Base class for converting from ints to/from human readable strings.""" |
| 54 | |
| 55 | def __init__(self, num_reserved_ids=NUM_RESERVED_TOKENS): |
| 56 | self._num_reserved_ids = num_reserved_ids |
| 57 | |
| 58 | @property |
| 59 | def num_reserved_ids(self): |
| 60 | return self._num_reserved_ids |
| 61 | |
| 62 | def encode(self, s): |
| 63 | """Transform a human-readable string into a sequence of int ids. |
| 64 | |
| 65 | The ids should be in the range [num_reserved_ids, vocab_size). Ids [0, |
| 66 | num_reserved_ids) are reserved. |
| 67 | |
| 68 | EOS is not appended. |
| 69 | |
| 70 | Args: |
| 71 | s: human-readable string to be converted. |
| 72 | |
| 73 | Returns: |
| 74 | ids: list of integers |
| 75 | """ |
| 76 | return [int(w) + self._num_reserved_ids for w in s.split()] |
| 77 | |
| 78 | def decode(self, ids, strip_extraneous=False): |
| 79 | """Transform a sequence of int ids into a human-readable string. |
| 80 | |
| 81 | EOS is not expected in ids. |
| 82 | |
| 83 | Args: |
| 84 | ids: list of integers to be converted. |
| 85 | strip_extraneous: bool, whether to strip off extraneous tokens |
| 86 | (EOS and PAD). |
| 87 | |
| 88 | Returns: |
| 89 | s: human-readable string. |
| 90 | """ |
| 91 | if strip_extraneous: |
| 92 | ids = strip_ids(ids, list(range(self._num_reserved_ids or 0))) |
| 93 | return " ".join(self.decode_list(ids)) |
| 94 | |
| 95 | def decode_list(self, ids): |
| 96 | """Transform a sequence of int ids into a their string versions. |
| 97 | |
| 98 | This method supports transforming individual input/output ids to their |
| 99 | string versions so that sequence to/from text conversions can be visualized |
| 100 | in a human readable format. |
| 101 | |
| 102 | Args: |
| 103 | ids: list of integers to be converted. |
| 104 | |
| 105 | Returns: |
| 106 | strs: list of human-readable string. |
| 107 | """ |
| 108 | decoded_ids = [] |
| 109 | for id_ in ids: |
nothing calls this directly
no outgoing calls
no test coverage detected