1 /* Copyright 2022 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 #include "tensorflow_lite_support/cc/text/tokenizers/tokenizer_utils.h"
17
18 #include "absl/status/status.h"
19 #include "tensorflow_lite_support/cc/common.h"
20 #include "tensorflow_lite_support/cc/port/status_macros.h"
21 #include "tensorflow_lite_support/cc/text/tokenizers/regex_tokenizer.h"
22 #include "tensorflow_lite_support/metadata/metadata_schema_generated.h"
23 #include "utils/bert_tokenizer.h"
24
25 namespace tflite {
26 namespace support {
27 namespace text {
28 namespace tokenizer {
29
30 using ::tflite::SentencePieceTokenizerOptions;
31 using ::tflite::support::CreateStatusWithPayload;
32 using ::tflite::support::StatusOr;
33 using ::tflite::support::TfLiteSupportStatus;
34
35 namespace {
36
CheckAndLoadFirstAssociatedFile(const flatbuffers::Vector<flatbuffers::Offset<tflite::AssociatedFile>> * associated_files,const tflite::metadata::ModelMetadataExtractor * metadata_extractor)37 StatusOr<absl::string_view> CheckAndLoadFirstAssociatedFile(
38 const flatbuffers::Vector<flatbuffers::Offset<tflite::AssociatedFile>>*
39 associated_files,
40 const tflite::metadata::ModelMetadataExtractor* metadata_extractor) {
41 if (associated_files == nullptr || associated_files->size() < 1 ||
42 associated_files->Get(0)->name() == nullptr) {
43 return CreateStatusWithPayload(
44 absl::StatusCode::kInvalidArgument,
45 "Invalid vocab_file from input process unit.",
46 TfLiteSupportStatus::kMetadataInvalidTokenizerError);
47 }
48 ASSIGN_OR_RETURN(absl::string_view vocab_buffer,
49 metadata_extractor->GetAssociatedFile(
50 associated_files->Get(0)->name()->str()));
51 return vocab_buffer;
52 }
53 } // namespace
54
CreateTokenizerFromProcessUnit(const tflite::ProcessUnit * tokenizer_process_unit,const tflite::metadata::ModelMetadataExtractor * metadata_extractor)55 StatusOr<std::unique_ptr<Tokenizer>> CreateTokenizerFromProcessUnit(
56 const tflite::ProcessUnit* tokenizer_process_unit,
57 const tflite::metadata::ModelMetadataExtractor* metadata_extractor) {
58 if (metadata_extractor == nullptr || tokenizer_process_unit == nullptr) {
59 return CreateStatusWithPayload(
60 absl::StatusCode::kInvalidArgument,
61 "No metadata or input process unit found.",
62 TfLiteSupportStatus::kMetadataInvalidTokenizerError);
63 }
64 switch (tokenizer_process_unit->options_type()) {
65 case ProcessUnitOptions_BertTokenizerOptions: {
66 const tflite::BertTokenizerOptions* options =
67 tokenizer_process_unit->options_as<tflite::BertTokenizerOptions>();
68 ASSIGN_OR_RETURN(absl::string_view vocab_buffer,
69 CheckAndLoadFirstAssociatedFile(options->vocab_file(),
70 metadata_extractor));
71 return absl::make_unique<libtextclassifier3::BertTokenizer>(
72 vocab_buffer.data(), vocab_buffer.size());
73 }
74 case ProcessUnitOptions_RegexTokenizerOptions: {
75 const tflite::RegexTokenizerOptions* options =
76 tokenizer_process_unit->options_as<RegexTokenizerOptions>();
77 ASSIGN_OR_RETURN(absl::string_view vocab_buffer,
78 CheckAndLoadFirstAssociatedFile(options->vocab_file(),
79 metadata_extractor));
80 if (options->delim_regex_pattern() == nullptr) {
81 return CreateStatusWithPayload(
82 absl::StatusCode::kInvalidArgument,
83 "Invalid delim_regex_pattern from input process unit.",
84 TfLiteSupportStatus::kMetadataInvalidTokenizerError);
85 }
86
87 std::unique_ptr<RegexTokenizer> regex_tokenizer =
88 absl::make_unique<RegexTokenizer>(
89 options->delim_regex_pattern()->str(), vocab_buffer.data(),
90 vocab_buffer.size());
91
92 int unknown_token_id = 0;
93 if (!regex_tokenizer->GetUnknownToken(&unknown_token_id)) {
94 return CreateStatusWithPayload(
95 absl::StatusCode::kInvalidArgument,
96 "RegexTokenizer doesn't have <UNKNOWN> token.",
97 TfLiteSupportStatus::kMetadataInvalidTokenizerError);
98 }
99
100 int pad_token_id = 0;
101 if (!regex_tokenizer->GetPadToken(&pad_token_id)) {
102 return CreateStatusWithPayload(
103 absl::StatusCode::kInvalidArgument,
104 "RegexTokenizer doesn't have <PAD> token.",
105 TfLiteSupportStatus::kMetadataInvalidTokenizerError);
106 }
107
108 return regex_tokenizer;
109 }
110 default:
111 return CreateStatusWithPayload(
112 absl::StatusCode::kNotFound,
113 absl::StrCat("Incorrect options_type:",
114 tokenizer_process_unit->options_type()),
115 TfLiteSupportStatus::kMetadataInvalidTokenizerError);
116 }
117 }
118
119 } // namespace tokenizer
120 } // namespace text
121 } // namespace support
122 } // namespace tflite
123
124