-
Notifications
You must be signed in to change notification settings - Fork 3
/
tokenizers.py
59 lines (39 loc) · 1.34 KB
/
tokenizers.py
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
import torch
import pickle
import nltk
from preprocessing import Text2Char
class TokenizerBase(object):
def __init__(self):
pass
def tokenize_text(self, text):
return text
def tokenize_texts(self, texts):
return texts
class WordTokenizer(TokenizerBase):
def __init__(self, vocab_path):
super(WordTokenizer, self).__init__()
self.vocab = pickle.load(open(vocab_path, 'rb'))
self.vocab_size = len(self.vocab)
def tokenize_text(self, text):
vocab = self.vocab
# Convert caption (string) to word ids.
tokens = nltk.tokenize.word_tokenize(
str(text).lower().decode('utf-8'))
caption = []
caption.append(vocab('<start>'))
caption.extend([vocab(token) for token in tokens])
caption.append(vocab('<end>'))
target = torch.Tensor(caption)
return target
def tokenize_texts(self, texts):
return texts
class CharacterTokenizer(TokenizerBase):
def __init__(self):
super(CharacterTokenizer, self).__init__()
self.encoder = Text2Char()
def tokenize_text(self, text):
caption = self.encoder.encode_text(text)
target = torch.LongTensor(caption)
return target
def tokenize_texts(self, texts):
return texts