File size: 1,696 Bytes
8016893
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json

class CharTokenizer:
    def __init__(self, max_len=100):
        self.char2idx = {}
        self.idx2char = {}
        self.max_len = max_len
        self.pad_token = "<PAD>"
        self.unk_token = "<UNK>"
        self.add_token(self.pad_token)
        self.add_token(self.unk_token)

    def add_token(self, token):
        if token not in self.char2idx:
            idx = len(self.char2idx)
            self.char2idx[token] = idx
            self.idx2char[idx] = token

    def build_vocab(self, texts):
        unique_chars = set()
        for text in texts:
            unique_chars.update(list(text))
        
        for char in sorted(list(unique_chars)):
            self.add_token(char)
            
    def encode(self, text):
        indices = [self.char2idx.get(char, self.char2idx[self.unk_token]) for char in text]
        
        if len(indices) > self.max_len:
            indices = indices[:self.max_len]
        
        padding = [self.char2idx[self.pad_token]] * (self.max_len - len(indices))
        return indices + padding

    def save(self, path):
        with open(path, 'w', encoding='utf-8') as f:
            json.dump({
                'char2idx': self.char2idx, 
                'max_len': self.max_len
            }, f, ensure_ascii=False, indent=2)

    @classmethod
    def load(cls, path):
        with open(path, 'r', encoding='utf-8') as f:
            data = json.load(f)
        
        tokenizer = cls(max_len=data['max_len'])
        tokenizer.char2idx = data['char2idx']
        tokenizer.idx2char = {int(v): k for k, v in data['char2idx'].items()}
        return tokenizer
    
    def __len__(self):
        return len(self.char2idx)