Pumponchik commited on
Commit
bb43d66
·
verified ·
1 Parent(s): 15012bd

Upload 4 files

Browse files
Files changed (1) hide show
  1. tokenizer.py +26 -0
tokenizer.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import defaultdict
2
+ import pickle
3
+
4
+ class CaptionTokenizer:
5
+ def __init__(self, tok_to_ind, ind_to_tok, vocab_freq, min_freq=5):
6
+ self.tok_to_ind = tok_to_ind
7
+ self.ind_to_tok = ind_to_tok
8
+ self.vocab_freq = vocab_freq
9
+ self.min_freq = min_freq
10
+ self.vocab_size = len(tok_to_ind)
11
+
12
+ def encode(self, text):
13
+ return [self.tok_to_ind[tok] if tok in self.tok_to_ind and self.vocab_freq[tok] >= self.min_freq else 0
14
+ for tok in text.split()]
15
+
16
+ def decode(self, indices):
17
+ return " ".join([self.ind_to_tok[idx] for idx in indices if idx in self.ind_to_tok and idx != 0])
18
+
19
+ def save(self, path):
20
+ with open(path, 'wb') as f:
21
+ pickle.dump(self, f)
22
+
23
+ @classmethod
24
+ def load(cls, path):
25
+ with open(path, 'rb') as f:
26
+ return pickle.load(f)