1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #ifndef TENSORFLOW_LITE_SUPPORT_CC_TEXT_TOKENIZERS_SENTENCEPIECE_TOKENIZER_H_
17 #define TENSORFLOW_LITE_SUPPORT_CC_TEXT_TOKENIZERS_SENTENCEPIECE_TOKENIZER_H_
18 
19 #include <fstream>
20 #include <string>
21 #include <vector>
22 
23 #include "src/sentencepiece_processor.h"
24 #include "tensorflow_lite_support/cc/text/tokenizers/tokenizer.h"
25 
26 namespace tflite {
27 namespace support {
28 namespace text {
29 namespace tokenizer {
30 
31 // SentencePiece tokenizer. Initialized with a model file.
32 class SentencePieceTokenizer : public Tokenizer {
33  public:
34   // Initialize the SentencePiece tokenizer from model file path.
SentencePieceTokenizer(const std::string & path_to_model)35   explicit SentencePieceTokenizer(const std::string& path_to_model) {
36     CHECK_OK(sp_.Load(path_to_model));
37   }
38 
SentencePieceTokenizer(const char * spmodel_buffer_data,size_t spmodel_buffer_size)39   explicit SentencePieceTokenizer(const char* spmodel_buffer_data,
40                                   size_t spmodel_buffer_size) {
41     absl::string_view buffer_binary(spmodel_buffer_data, spmodel_buffer_size);
42     CHECK_OK(sp_.LoadFromSerializedProto(buffer_binary));
43   }
44 
45   // Perform tokenization, return tokenized results.
Tokenize(const std::string & input)46   TokenizerResult Tokenize(const std::string& input) override {
47     TokenizerResult result;
48     std::vector<std::string>& subwords = result.subwords;
49     CHECK_OK(sp_.Encode(input, &subwords));
50     return result;
51   }
52 
53   // Find the id of a string token.
LookupId(absl::string_view key,int * result)54   bool LookupId(absl::string_view key, int* result) const override {
55     *result = sp_.PieceToId(key);
56     return true;
57   }
58 
59   // Find the string token of an id.
LookupWord(int vocab_id,absl::string_view * result)60   bool LookupWord(int vocab_id, absl::string_view* result) const override {
61     *result = sp_.IdToPiece(vocab_id);
62     return true;
63   }
64 
65  private:
66   sentencepiece::SentencePieceProcessor sp_;
67 };
68 
69 }  // namespace tokenizer
70 }  // namespace text
71 }  // namespace support
72 }  // namespace tflite
73 
74 #endif  // TENSORFLOW_LITE_SUPPORT_CC_TEXT_TOKENIZERS_SENTENCEPIECE_TOKENIZER_H_
75