normalize.cc revision 6b6244c40197b34f49bb50aa52efb082380d4637
1/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
2
3Licensed under the Apache License, Version 2.0 (the "License");
4you may not use this file except in compliance with the License.
5You may obtain a copy of the License at
6
7    http://www.apache.org/licenses/LICENSE-2.0
8
9Unless required by applicable law or agreed to in writing, software
10distributed under the License is distributed on an "AS IS" BASIS,
11WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12See the License for the specific language governing permissions and
13limitations under the License.
14==============================================================================*/
15
16// Normalize the string input.
17//
18// Input:
19//     Input[0]: One sentence. string[1]
20//
21// Output:
22//     Output[0]: Normalized sentence. string[1]
23//
24
25#include <algorithm>
26#include <string>
27
28#include "absl/strings/str_cat.h"
29#include "absl/strings/strip.h"
30#include "re2/re2.h"
31#include "tensorflow/contrib/lite/context.h"
32#include "tensorflow/contrib/lite/kernels/kernel_util.h"
33#include "tensorflow/contrib/lite/string_util.h"
34
35namespace tflite {
36namespace ops {
37namespace custom {
38
39namespace normalize {
40
41// Predictor transforms.
42const char kPunctuationsRegex[] = "[.*()\"]";
43
44const std::map<string, string>* kRegexTransforms =
45    new std::map<string, string>({
46        {"([^\\s]+)n't", "\\1 not"},
47        {"([^\\s]+)'nt", "\\1 not"},
48        {"([^\\s]+)'ll", "\\1 will"},
49        {"([^\\s]+)'re", "\\1 are"},
50        {"([^\\s]+)'ve", "\\1 have"},
51        {"i'm", "i am"},
52    });
53
54static const char kStartToken[] = "<S>";
55static const char kEndToken[] = "<E>";
56static const int32_t kMaxInputChars = 300;
57
58TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) {
59  tflite::StringRef input = tflite::GetString(GetInput(context, node, 0), 0);
60
61  string result(absl::AsciiStrToLower(absl::string_view(input.str, input.len)));
62  absl::StripAsciiWhitespace(&result);
63  // Do not remove commas, semi-colons or colons from the sentences as they can
64  // indicate the beginning of a new clause.
65  RE2::GlobalReplace(&result, kPunctuationsRegex, "");
66  RE2::GlobalReplace(&result, "\\s('t|'nt|n't|'d|'ll|'s|'m|'ve|'re)([\\s,;:/])",
67                     "\\1\\2");
68  RE2::GlobalReplace(&result, "\\s('t|'nt|n't|'d|'ll|'s|'m|'ve|'re)$", "\\1");
69  for (auto iter = kRegexTransforms->begin(); iter != kRegexTransforms->end();
70       iter++) {
71    RE2::GlobalReplace(&result, iter->first, iter->second);
72  }
73
74  // Treat questions & interjections as special cases.
75  RE2::GlobalReplace(&result, "([?])+", "\\1");
76  RE2::GlobalReplace(&result, "([!])+", "\\1");
77  RE2::GlobalReplace(&result, "([^?!]+)([?!])", "\\1 \\2 ");
78  RE2::GlobalReplace(&result, "([?!])([?!])", "\\1 \\2");
79
80  RE2::GlobalReplace(&result, "[\\s,:;\\-&'\"]+$", "");
81  RE2::GlobalReplace(&result, "^[\\s,:;\\-&'\"]+", "");
82  absl::StripAsciiWhitespace(&result);
83
84  // Add start and end token.
85  // Truncate input to maximum allowed size.
86  if (result.length() <= kMaxInputChars) {
87    absl::StrAppend(&result, " ", kEndToken);
88  } else {
89    result = result.substr(0, kMaxInputChars);
90  }
91  result = absl::StrCat(kStartToken, " ", result);
92
93  tflite::DynamicBuffer buf;
94  buf.AddString(result.data(), result.length());
95  buf.WriteToTensor(GetOutput(context, node, 0));
96  return kTfLiteOk;
97}
98
99}  // namespace normalize
100
101TfLiteRegistration* Register_NORMALIZE() {
102  static TfLiteRegistration r = {nullptr, nullptr, nullptr, normalize::Eval};
103  return &r;
104}
105
106}  // namespace custom
107}  // namespace ops
108}  // namespace tflite
109