aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/lite/models/smartreply/predictor_test.cc
blob: 2fa9923bc93d7e559884b6880187637b78f4b217 (plain)
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/contrib/lite/models/smartreply/predictor.h"

#include <fstream>
#include <unordered_set>

#include "base/logging.h"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/strings/str_cat.h"
#include "absl/strings/str_split.h"
#include "tensorflow/contrib/lite/models/test_utils.h"

namespace tflite {
namespace custom {
namespace smartreply {
namespace {

const char kModelName[] = "smartreply_ondevice_model.bin";
const char kSamples[] = "smartreply_samples.tsv";

MATCHER_P(IncludeAnyResponesIn, expected_response, "contains the response") {
  bool has_expected_response = false;
  for (const auto &item : *arg) {
    const string &response = item.GetText();
    if (expected_response.find(response) != expected_response.end()) {
      has_expected_response = true;
      break;
    }
  }
  return has_expected_response;
}

class PredictorTest : public ::testing::Test {
 protected:
  PredictorTest() {
    model_ = tflite::FlatBufferModel::BuildFromFile(
        StrCat(TestDataPath(), "/", kModelName).c_str());
    CHECK(model_);
  }
  ~PredictorTest() override {}

  std::unique_ptr<::tflite::FlatBufferModel> model_;
};

TEST_F(PredictorTest, GetSegmentPredictions) {
  std::vector<PredictorResponse> predictions;

  GetSegmentPredictions({"Welcome"}, *model_, /*config=*/{{}}, &predictions);
  EXPECT_GT(predictions.size(), 0);

  float max = 0;
  for (const auto &item : predictions) {
    LOG(INFO) << "Response: " << item.GetText();
    if (item.GetScore() > max) {
      max = item.GetScore();
    }
  }

  EXPECT_GT(max, 0.3);
  EXPECT_THAT(
      &predictions,
      IncludeAnyResponesIn(std::unordered_set<string>({"Thanks very much"})));
}

TEST_F(PredictorTest, TestTwoSentences) {
  std::vector<PredictorResponse> predictions;

  GetSegmentPredictions({"Hello", "How are you?"}, *model_, /*config=*/{{}},
                        &predictions);
  EXPECT_GT(predictions.size(), 0);

  float max = 0;
  for (const auto &item : predictions) {
    LOG(INFO) << "Response: " << item.GetText();
    if (item.GetScore() > max) {
      max = item.GetScore();
    }
  }

  EXPECT_GT(max, 0.3);
  EXPECT_THAT(&predictions, IncludeAnyResponesIn(std::unordered_set<string>(
                                {"Hi, how are you doing?"})));
}

TEST_F(PredictorTest, TestBackoff) {
  std::vector<PredictorResponse> predictions;

  GetSegmentPredictions({"你好"}, *model_, /*config=*/{{}}, &predictions);
  EXPECT_EQ(predictions.size(), 0);

  // Backoff responses are returned in order.
  GetSegmentPredictions({"你好"}, *model_, /*config=*/{{"Yes", "Ok"}},
                        &predictions);
  EXPECT_EQ(predictions.size(), 2);
  EXPECT_EQ(predictions[0].GetText(), "Yes");
  EXPECT_EQ(predictions[1].GetText(), "Ok");
}

TEST_F(PredictorTest, BatchTest) {
  int total_items = 0;
  int total_responses = 0;
  int total_triggers = 0;

  string line;
  std::ifstream fin(StrCat(TestDataPath(), "/", kSamples));
  while (std::getline(fin, line)) {
    const std::vector<string> &fields = strings::Split(line, '\t');
    if (fields.empty()) {
      continue;
    }

    // Parse sample file and predict
    const string &msg = fields[0];
    std::vector<PredictorResponse> predictions;
    GetSegmentPredictions({msg}, *model_, /*config=*/{{}}, &predictions);

    // Validate response and generate stats.
    total_items++;
    total_responses += predictions.size();
    if (!predictions.empty()) {
      total_triggers++;
    }
    EXPECT_THAT(&predictions, IncludeAnyResponesIn(std::unordered_set<string>(
                                  fields.begin() + 1, fields.end())));
  }

  LOG(INFO) << "Responses: " << total_responses << " / " << total_items;
  LOG(INFO) << "Triggers: " << total_triggers << " / " << total_items;
  EXPECT_EQ(total_triggers, total_items);
}

}  // namespace
}  // namespace smartreply
}  // namespace custom
}  // namespace tflite