blob: e6f33d6131e80e79ab518a62bf724f958dfd6c60 [file] [log] [blame]
Matt Sharifibda09f12017-03-10 12:29:15 +01001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// Feature processing for FFModel (feed-forward SmartSelection model).
18
Lukas Zilkab23e2122018-02-09 10:25:19 +010019#ifndef LIBTEXTCLASSIFIER_FEATURE_PROCESSOR_H_
20#define LIBTEXTCLASSIFIER_FEATURE_PROCESSOR_H_
Matt Sharifibda09f12017-03-10 12:29:15 +010021
Lukas Zilka21d8c982018-01-24 11:11:20 +010022#include <map>
Matt Sharifibda09f12017-03-10 12:29:15 +010023#include <memory>
Lukas Zilkae5ea2ab2017-10-11 10:50:05 +020024#include <set>
Matt Sharifibda09f12017-03-10 12:29:15 +010025#include <string>
26#include <vector>
27
Lukas Zilka21d8c982018-01-24 11:11:20 +010028#include "cached-features.h"
29#include "model_generated.h"
30#include "token-feature-extractor.h"
31#include "tokenizer.h"
32#include "types.h"
33#include "util/base/integral_types.h"
Lukas Zilka6bb39a82017-04-07 19:55:11 +020034#include "util/base/logging.h"
Matt Sharifif95c3bd2017-04-25 18:41:11 +020035#include "util/utf8/unicodetext.h"
Lukas Zilka21d8c982018-01-24 11:11:20 +010036#include "util/utf8/unilib.h"
Matt Sharifibda09f12017-03-10 12:29:15 +010037
Lukas Zilka21d8c982018-01-24 11:11:20 +010038namespace libtextclassifier2 {
Matt Sharifibda09f12017-03-10 12:29:15 +010039
40constexpr int kInvalidLabel = -1;
41
42namespace internal {
43
Matt Sharifibda09f12017-03-10 12:29:15 +010044TokenFeatureExtractorOptions BuildTokenFeatureExtractorOptions(
Lukas Zilka21d8c982018-01-24 11:11:20 +010045 const FeatureProcessorOptions* options);
Matt Sharifibda09f12017-03-10 12:29:15 +010046
Matt Sharifibda09f12017-03-10 12:29:15 +010047// Splits tokens that contain the selection boundary inside them.
48// E.g. "foo{bar}@google.com" -> "foo", "bar", "@google.com"
49void SplitTokensOnSelectionBoundaries(CodepointSpan selection,
50 std::vector<Token>* tokens);
51
Matt Sharifibe876dc2017-03-17 17:02:43 +010052// Returns the index of token that corresponds to the codepoint span.
53int CenterTokenFromClick(CodepointSpan span, const std::vector<Token>& tokens);
54
55// Returns the index of token that corresponds to the middle of the codepoint
56// span.
57int CenterTokenFromMiddleOfSelection(
58 CodepointSpan span, const std::vector<Token>& selectable_tokens);
59
Lukas Zilka6bb39a82017-04-07 19:55:11 +020060// Strips the tokens from the tokens vector that are not used for feature
61// extraction because they are out of scope, or pads them so that there is
62// enough tokens in the required context_size for all inferences with a click
63// in relative_click_span.
64void StripOrPadTokens(TokenSpan relative_click_span, int context_size,
65 std::vector<Token>* tokens, int* click_pos);
66
Lukas Zilka21d8c982018-01-24 11:11:20 +010067// If unilib is not nullptr, just returns unilib. Otherwise, if unilib is
68// nullptr, will create UniLib, assign ownership to owned_unilib, and return it.
Lukas Zilkab23e2122018-02-09 10:25:19 +010069const UniLib* MaybeCreateUnilib(const UniLib* unilib,
70 std::unique_ptr<UniLib>* owned_unilib);
Lukas Zilka21d8c982018-01-24 11:11:20 +010071
Matt Sharifibda09f12017-03-10 12:29:15 +010072} // namespace internal
73
Lukas Zilka40c18de2017-04-10 17:22:22 +020074// Converts a codepoint span to a token span in the given list of tokens.
Lukas Zilka726b4d22017-12-13 16:37:03 +010075// If snap_boundaries_to_containing_tokens is set to true, it is enough for a
76// token to overlap with the codepoint range to be considered part of it.
77// Otherwise it must be fully included in the range.
78TokenSpan CodepointSpanToTokenSpan(
79 const std::vector<Token>& selectable_tokens, CodepointSpan codepoint_span,
80 bool snap_boundaries_to_containing_tokens = false);
Matt Sharifibda09f12017-03-10 12:29:15 +010081
Lukas Zilka40c18de2017-04-10 17:22:22 +020082// Converts a token span to a codepoint span in the given list of tokens.
83CodepointSpan TokenSpanToCodepointSpan(
84 const std::vector<Token>& selectable_tokens, TokenSpan token_span);
85
Lukas Zilka6bb39a82017-04-07 19:55:11 +020086// Takes care of preparing features for the span prediction model.
Matt Sharifibda09f12017-03-10 12:29:15 +010087class FeatureProcessor {
88 public:
Lukas Zilka21d8c982018-01-24 11:11:20 +010089 // If unilib is nullptr, will create and own an instance of a UniLib,
90 // otherwise will use what's passed in.
91 explicit FeatureProcessor(const FeatureProcessorOptions* options,
Lukas Zilkab23e2122018-02-09 10:25:19 +010092 const UniLib* unilib = nullptr)
Lukas Zilka21d8c982018-01-24 11:11:20 +010093 : owned_unilib_(nullptr),
94 unilib_(internal::MaybeCreateUnilib(unilib, &owned_unilib_)),
95 feature_extractor_(internal::BuildTokenFeatureExtractorOptions(options),
96 *unilib_),
Lukas Zilka6bb39a82017-04-07 19:55:11 +020097 options_(options),
Lukas Zilka21d8c982018-01-24 11:11:20 +010098 tokenizer_(
99 options->tokenization_codepoint_config() != nullptr
100 ? Tokenizer({options->tokenization_codepoint_config()->begin(),
101 options->tokenization_codepoint_config()->end()},
102 options->tokenize_on_script_change())
103 : Tokenizer({}, /*split_on_script_change=*/false)) {
Matt Sharifibda09f12017-03-10 12:29:15 +0100104 MakeLabelMaps();
Lukas Zilka21d8c982018-01-24 11:11:20 +0100105 if (options->supported_codepoint_ranges() != nullptr) {
106 PrepareCodepointRanges({options->supported_codepoint_ranges()->begin(),
107 options->supported_codepoint_ranges()->end()},
108 &supported_codepoint_ranges_);
109 }
110 if (options->internal_tokenizer_codepoint_ranges() != nullptr) {
111 PrepareCodepointRanges(
112 {options->internal_tokenizer_codepoint_ranges()->begin(),
113 options->internal_tokenizer_codepoint_ranges()->end()},
114 &internal_tokenizer_codepoint_ranges_);
115 }
Lukas Zilkae5ea2ab2017-10-11 10:50:05 +0200116 PrepareIgnoredSpanBoundaryCodepoints();
Matt Sharifibda09f12017-03-10 12:29:15 +0100117 }
118
Matt Sharifibda09f12017-03-10 12:29:15 +0100119 // Tokenizes the input string using the selected tokenization method.
Lukas Zilkab23e2122018-02-09 10:25:19 +0100120 std::vector<Token> Tokenize(const std::string& text) const;
121
122 // Same as above but takes UnicodeText.
123 std::vector<Token> Tokenize(const UnicodeText& text_unicode) const;
Matt Sharifibda09f12017-03-10 12:29:15 +0100124
Matt Sharifibda09f12017-03-10 12:29:15 +0100125 // Converts a label into a token span.
126 bool LabelToTokenSpan(int label, TokenSpan* token_span) const;
127
Lukas Zilka6bb39a82017-04-07 19:55:11 +0200128 // Gets the total number of selection labels.
129 int GetSelectionLabelCount() const { return label_to_selection_.size(); }
130
Matt Sharifibda09f12017-03-10 12:29:15 +0100131 // Gets the string value for given collection label.
132 std::string LabelToCollection(int label) const;
133
134 // Gets the total number of collections of the model.
135 int NumCollections() const { return collection_to_label_.size(); }
136
137 // Gets the name of the default collection.
Lukas Zilka6bb39a82017-04-07 19:55:11 +0200138 std::string GetDefaultCollection() const;
139
Lukas Zilka21d8c982018-01-24 11:11:20 +0100140 const FeatureProcessorOptions* GetOptions() const { return options_; }
Lukas Zilka6bb39a82017-04-07 19:55:11 +0200141
142 // Tokenizes the context and input span, and finds the click position.
143 void TokenizeAndFindClick(const std::string& context,
144 CodepointSpan input_span,
Lukas Zilkab23e2122018-02-09 10:25:19 +0100145 bool only_use_line_with_click,
146 std::vector<Token>* tokens, int* click_pos) const;
147
148 // Same as above but takes UnicodeText.
149 void TokenizeAndFindClick(const UnicodeText& context_unicode,
150 CodepointSpan input_span,
151 bool only_use_line_with_click,
Lukas Zilka6bb39a82017-04-07 19:55:11 +0200152 std::vector<Token>* tokens, int* click_pos) const;
153
154 // Extracts features as a CachedFeatures object that can be used for repeated
155 // inference over token spans in the given context.
Lukas Zilka21d8c982018-01-24 11:11:20 +0100156 bool ExtractFeatures(const std::vector<Token>& tokens, TokenSpan token_span,
Lukas Zilkab23e2122018-02-09 10:25:19 +0100157 CodepointSpan selection_span_for_feature,
Lukas Zilka21d8c982018-01-24 11:11:20 +0100158 EmbeddingExecutor* embedding_executor,
159 int feature_vector_size,
Lukas Zilka6bb39a82017-04-07 19:55:11 +0200160 std::unique_ptr<CachedFeatures>* cached_features) const;
161
162 // Fills selection_label_spans with CodepointSpans that correspond to the
163 // selection labels. The CodepointSpans are based on the codepoint ranges of
164 // given tokens.
165 bool SelectionLabelSpans(
166 VectorSpan<Token> tokens,
167 std::vector<CodepointSpan>* selection_label_spans) const;
168
169 int DenseFeaturesCount() const {
170 return feature_extractor_.DenseFeaturesCount();
Matt Sharifibda09f12017-03-10 12:29:15 +0100171 }
172
Lukas Zilka21d8c982018-01-24 11:11:20 +0100173 int EmbeddingSize() const { return options_->embedding_size(); }
174
Lukas Zilkab23e2122018-02-09 10:25:19 +0100175 // Splits context to several segments.
Lukas Zilka726b4d22017-12-13 16:37:03 +0100176 std::vector<UnicodeTextRange> SplitContext(
177 const UnicodeText& context_unicode) const;
178
Lukas Zilkae5ea2ab2017-10-11 10:50:05 +0200179 // Strips boundary codepoints from the span in context and returns the new
180 // start and end indices. If the span comprises entirely of boundary
181 // codepoints, the first index of span is returned for both indices.
182 CodepointSpan StripBoundaryCodepoints(const std::string& context,
183 CodepointSpan span) const;
184
Lukas Zilkab23e2122018-02-09 10:25:19 +0100185 // Same as above but takes UnicodeText.
186 CodepointSpan StripBoundaryCodepoints(const UnicodeText& context_unicode,
187 CodepointSpan span) const;
188
Matt Sharifibda09f12017-03-10 12:29:15 +0100189 protected:
Lukas Zilka26e8c2e2017-04-06 15:54:24 +0200190 // Represents a codepoint range [start, end).
191 struct CodepointRange {
192 int32 start;
193 int32 end;
194
195 CodepointRange(int32 arg_start, int32 arg_end)
196 : start(arg_start), end(arg_end) {}
197 };
198
Matt Sharifibda09f12017-03-10 12:29:15 +0100199 // Returns the class id corresponding to the given string collection
200 // identifier. There is a catch-all class id that the function returns for
201 // unknown collections.
202 int CollectionToLabel(const std::string& collection) const;
203
204 // Prepares mapping from collection names to labels.
205 void MakeLabelMaps();
206
207 // Gets the number of spannable tokens for the model.
208 //
209 // Spannable tokens are those tokens of context, which the model predicts
210 // selection spans over (i.e., there is 1:1 correspondence between the output
211 // classes of the model and each of the spannable tokens).
Lukas Zilka21d8c982018-01-24 11:11:20 +0100212 int GetNumContextTokens() const { return options_->context_size() * 2 + 1; }
Matt Sharifibda09f12017-03-10 12:29:15 +0100213
214 // Converts a label into a span of codepoint indices corresponding to it
215 // given output_tokens.
Lukas Zilka6bb39a82017-04-07 19:55:11 +0200216 bool LabelToSpan(int label, const VectorSpan<Token>& output_tokens,
Matt Sharifibda09f12017-03-10 12:29:15 +0100217 CodepointSpan* span) const;
218
219 // Converts a span to the corresponding label given output_tokens.
220 bool SpanToLabel(const std::pair<CodepointIndex, CodepointIndex>& span,
221 const std::vector<Token>& output_tokens, int* label) const;
222
223 // Converts a token span to the corresponding label.
224 int TokenSpanToLabel(const std::pair<TokenIndex, TokenIndex>& span) const;
225
Matt Sharifif95c3bd2017-04-25 18:41:11 +0200226 void PrepareCodepointRanges(
Lukas Zilka21d8c982018-01-24 11:11:20 +0100227 const std::vector<const FeatureProcessorOptions_::CodepointRange*>&
Matt Sharifif95c3bd2017-04-25 18:41:11 +0200228 codepoint_ranges,
229 std::vector<CodepointRange>* prepared_codepoint_ranges);
Lukas Zilka26e8c2e2017-04-06 15:54:24 +0200230
231 // Returns the ratio of supported codepoints to total number of codepoints in
Lukas Zilka21d8c982018-01-24 11:11:20 +0100232 // the given token span.
233 float SupportedCodepointsRatio(const TokenSpan& token_span,
Lukas Zilka26e8c2e2017-04-06 15:54:24 +0200234 const std::vector<Token>& tokens) const;
235
Matt Sharifif95c3bd2017-04-25 18:41:11 +0200236 // Returns true if given codepoint is covered by the given sorted vector of
237 // codepoint ranges.
238 bool IsCodepointInRanges(
239 int codepoint, const std::vector<CodepointRange>& codepoint_ranges) const;
Lukas Zilka26e8c2e2017-04-06 15:54:24 +0200240
Lukas Zilkae5ea2ab2017-10-11 10:50:05 +0200241 void PrepareIgnoredSpanBoundaryCodepoints();
242
243 // Counts the number of span boundary codepoints. If count_from_beginning is
244 // True, the counting will start at the span_start iterator (inclusive) and at
245 // maximum end at span_end (exclusive). If count_from_beginning is True, the
246 // counting will start from span_end (exclusive) and end at span_start
247 // (inclusive).
248 int CountIgnoredSpanBoundaryCodepoints(
249 const UnicodeText::const_iterator& span_start,
250 const UnicodeText::const_iterator& span_end,
251 bool count_from_beginning) const;
252
Lukas Zilka6bb39a82017-04-07 19:55:11 +0200253 // Finds the center token index in tokens vector, using the method defined
254 // in options_.
255 int FindCenterToken(CodepointSpan span,
256 const std::vector<Token>& tokens) const;
257
Lukas Zilka40c18de2017-04-10 17:22:22 +0200258 // Tokenizes the input text using ICU tokenizer.
Lukas Zilkab23e2122018-02-09 10:25:19 +0100259 bool ICUTokenize(const UnicodeText& context_unicode,
Lukas Zilka40c18de2017-04-10 17:22:22 +0200260 std::vector<Token>* result) const;
261
Matt Sharifif95c3bd2017-04-25 18:41:11 +0200262 // Takes the result of ICU tokenization and retokenizes stretches of tokens
263 // made of a specific subset of characters using the internal tokenizer.
Lukas Zilkab23e2122018-02-09 10:25:19 +0100264 void InternalRetokenize(const UnicodeText& unicode_text,
Matt Sharifif95c3bd2017-04-25 18:41:11 +0200265 std::vector<Token>* tokens) const;
266
267 // Tokenizes a substring of the unicode string, appending the resulting tokens
268 // to the output vector. The resulting tokens have bounds relative to the full
269 // string. Does nothing if the start of the span is negative.
270 void TokenizeSubstring(const UnicodeText& unicode_text, CodepointSpan span,
271 std::vector<Token>* result) const;
272
Lukas Zilka726b4d22017-12-13 16:37:03 +0100273 // Removes all tokens from tokens that are not on a line (defined by calling
274 // SplitContext on the context) to which span points.
275 void StripTokensFromOtherLines(const std::string& context, CodepointSpan span,
276 std::vector<Token>* tokens) const;
277
Lukas Zilkab23e2122018-02-09 10:25:19 +0100278 // Same as above but takes UnicodeText.
279 void StripTokensFromOtherLines(const UnicodeText& context_unicode,
280 CodepointSpan span,
281 std::vector<Token>* tokens) const;
282
Lukas Zilka21d8c982018-01-24 11:11:20 +0100283 private:
284 std::unique_ptr<UniLib> owned_unilib_;
Lukas Zilkab23e2122018-02-09 10:25:19 +0100285 const UniLib* unilib_;
Lukas Zilka21d8c982018-01-24 11:11:20 +0100286
287 protected:
Lukas Zilka6bb39a82017-04-07 19:55:11 +0200288 const TokenFeatureExtractor feature_extractor_;
289
Matt Sharifif95c3bd2017-04-25 18:41:11 +0200290 // Codepoint ranges that define what codepoints are supported by the model.
291 // NOTE: Must be sorted.
292 std::vector<CodepointRange> supported_codepoint_ranges_;
293
294 // Codepoint ranges that define which tokens (consisting of which codepoints)
295 // should be re-tokenized with the internal tokenizer in the mixed
296 // tokenization mode.
297 // NOTE: Must be sorted.
298 std::vector<CodepointRange> internal_tokenizer_codepoint_ranges_;
299
Matt Sharifibda09f12017-03-10 12:29:15 +0100300 private:
Lukas Zilkae5ea2ab2017-10-11 10:50:05 +0200301 // Set of codepoints that will be stripped from beginning and end of
302 // predicted spans.
303 std::set<int32> ignored_span_boundary_codepoints_;
304
Lukas Zilka21d8c982018-01-24 11:11:20 +0100305 const FeatureProcessorOptions* const options_;
Matt Sharifibda09f12017-03-10 12:29:15 +0100306
307 // Mapping between token selection spans and labels ids.
308 std::map<TokenSpan, int> selection_to_label_;
309 std::vector<TokenSpan> label_to_selection_;
310
311 // Mapping between collections and labels.
312 std::map<std::string, int> collection_to_label_;
313
314 Tokenizer tokenizer_;
Matt Sharifibda09f12017-03-10 12:29:15 +0100315};
316
Lukas Zilka21d8c982018-01-24 11:11:20 +0100317} // namespace libtextclassifier2
Matt Sharifibda09f12017-03-10 12:29:15 +0100318
Lukas Zilkab23e2122018-02-09 10:25:19 +0100319#endif // LIBTEXTCLASSIFIER_FEATURE_PROCESSOR_H_