Download module_profanity/src/tokenizer.py from orcheflow/flow-moderation: direct link, hf CLI and curl.
- Browser
- Download file 1.7 kB
-
https://huggingface.co/orcheflow/flow-moderation/resolve/8eebeffbf500b78dd7d2eeffc268c2bc253f2052/module_profanity/src/tokenizer.py
- Command line
-
hf download hf://orcheflow/flow-moderation@8eebeffbf500b78dd7d2eeffc268c2bc253f2052/module_profanity/src/tokenizer.py
-
curl -L -o tokenizer.py https://huggingface.co/orcheflow/flow-moderation/resolve/8eebeffbf500b78dd7d2eeffc268c2bc253f2052/module_profanity/src/tokenizer.py
1.7 kB
| 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) | |
| 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) | |