PhraseTokenizer.py 4.46 KB
Newer Older
Rayyyyy's avatar
Rayyyyy committed
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
from typing import List, Iterable
import collections
import string
import os
import json
import logging
from .WordTokenizer import WordTokenizer, ENGLISH_STOP_WORDS
from transformers.utils.import_utils import is_nltk_available, NLTK_IMPORT_ERROR


logger = logging.getLogger(__name__)


class PhraseTokenizer(WordTokenizer):
    """Tokenizes the text with respect to existent phrases in the vocab.

    This tokenizers respects phrases that are in the vocab. Phrases are separated with 'ngram_separator', for example,
    in Google News word2vec file, ngrams are separated with a _ like New_York. These phrases are detected in text and merged as one special token. (New York is the ... => [New_York, is, the])
    """

    def __init__(
        self,
        vocab: Iterable[str] = [],
        stop_words: Iterable[str] = ENGLISH_STOP_WORDS,
        do_lower_case: bool = False,
        ngram_separator: str = "_",
        max_ngram_length: int = 5,
    ):
        if not is_nltk_available():
            raise ImportError(NLTK_IMPORT_ERROR.format(self.__class__.__name__))

        self.stop_words = set(stop_words)
        self.do_lower_case = do_lower_case
        self.ngram_separator = ngram_separator
        self.max_ngram_length = max_ngram_length
        self.set_vocab(vocab)

    def get_vocab(self):
        return self.vocab

    def set_vocab(self, vocab: Iterable[str]):
        self.vocab = vocab
        self.word2idx = collections.OrderedDict([(word, idx) for idx, word in enumerate(vocab)])

        # Check for ngram in vocab
        self.ngram_lookup = set()
        self.ngram_lengths = set()
        for word in vocab:
            if self.ngram_separator is not None and self.ngram_separator in word:
                # Sum words might me malformed in e.g. google news word2vec, containing two or more _ after each other
                ngram_count = word.count(self.ngram_separator) + 1
                if self.ngram_separator + self.ngram_separator not in word and ngram_count <= self.max_ngram_length:
                    self.ngram_lookup.add(word)
                    self.ngram_lengths.add(ngram_count)

        if len(vocab) > 0:
            logger.info("PhraseTokenizer - Phrase ngram lengths: {}".format(self.ngram_lengths))
            logger.info("PhraseTokenizer - Num phrases: {}".format(len(self.ngram_lookup)))

    def tokenize(self, text: str, **kwargs) -> List[int]:
        from nltk import word_tokenize

        tokens = word_tokenize(text, preserve_line=True)

        # phrase detection
        for ngram_len in sorted(self.ngram_lengths, reverse=True):
            idx = 0
            while idx <= len(tokens) - ngram_len:
                ngram = self.ngram_separator.join(tokens[idx : idx + ngram_len])
                if ngram in self.ngram_lookup:
                    tokens[idx : idx + ngram_len] = [ngram]
                elif ngram.lower() in self.ngram_lookup:
                    tokens[idx : idx + ngram_len] = [ngram.lower()]
                idx += 1

        # Map tokens to idx, filter stop words
        tokens_filtered = []
        for token in tokens:
            if token in self.stop_words:
                continue
            elif token in self.word2idx:
                tokens_filtered.append(self.word2idx[token])
                continue

            token = token.lower()
            if token in self.stop_words:
                continue
            elif token in self.word2idx:
                tokens_filtered.append(self.word2idx[token])
                continue

            token = token.strip(string.punctuation)
            if token in self.stop_words:
                continue
            elif len(token) > 0 and token in self.word2idx:
                tokens_filtered.append(self.word2idx[token])
                continue

        return tokens_filtered

    def save(self, output_path: str):
        with open(os.path.join(output_path, "phrasetokenizer_config.json"), "w") as fOut:
            json.dump(
                {
                    "vocab": list(self.word2idx.keys()),
                    "stop_words": list(self.stop_words),
                    "do_lower_case": self.do_lower_case,
                    "ngram_separator": self.ngram_separator,
                    "max_ngram_length": self.max_ngram_length,
                },
                fOut,
            )

    @staticmethod
    def load(input_path: str):
        with open(os.path.join(input_path, "phrasetokenizer_config.json"), "r") as fIn:
            config = json.load(fIn)

        return PhraseTokenizer(**config)