blob: ca05dfd162ca6174cb40f9c08a0a72c687f6fbe4 [file] [log] [blame]
Andrew Moylanff6be512018-07-03 11:05:01 +10001// Copyright 2018 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "ml/machine_learning_service_impl.h"
alanlxlcb1f8562018-11-01 15:16:11 +11006#include "ml/request_metrics.h"
Andrew Moylanff6be512018-07-03 11:05:01 +10007
Michael Martisa74af932018-08-13 16:52:36 +10008#include <memory>
Andrew Moylanff6be512018-07-03 11:05:01 +10009#include <utility>
10
Michael Martisa74af932018-08-13 16:52:36 +100011#include <base/bind.h>
12#include <base/bind_helpers.h>
Honglin Yuf33dce32019-12-05 15:10:39 +110013#include <base/files/file.h>
14#include <base/files/file_util.h>
Michael Martis8783c8e2019-06-26 17:30:54 +100015#include <tensorflow/lite/model.h>
Honglin Yuf33dce32019-12-05 15:10:39 +110016#include <unicode/putil.h>
17#include <unicode/udata.h>
18#include <utils/memory/mmap.h>
Michael Martisa74af932018-08-13 16:52:36 +100019
charleszhao17777f92020-04-23 12:53:11 +100020#include "ml/handwriting.h"
charleszhao05c5a4a2020-06-09 16:49:54 +100021#include "ml/handwriting_path.h"
charleszhao17777f92020-04-23 12:53:11 +100022#include "ml/handwriting_recognizer_impl.h"
Michael Martisa74af932018-08-13 16:52:36 +100023#include "ml/model_impl.h"
charleszhao17777f92020-04-23 12:53:11 +100024#include "ml/mojom/handwriting_recognizer.mojom.h"
Hidehiko Abeaa488c32018-08-31 23:49:41 +090025#include "ml/mojom/model.mojom.h"
Honglin Yuf33dce32019-12-05 15:10:39 +110026#include "ml/text_classifier_impl.h"
Michael Martisa74af932018-08-13 16:52:36 +100027
Andrew Moylanff6be512018-07-03 11:05:01 +100028namespace ml {
29
Michael Martisa74af932018-08-13 16:52:36 +100030namespace {
31
Honglin Yu0ed72352019-08-27 17:42:01 +100032using ::chromeos::machine_learning::mojom::BuiltinModelId;
33using ::chromeos::machine_learning::mojom::BuiltinModelSpecPtr;
34using ::chromeos::machine_learning::mojom::FlatBufferModelSpecPtr;
charleszhao17777f92020-04-23 12:53:11 +100035using ::chromeos::machine_learning::mojom::HandwritingRecognizerRequest;
charleszhao05c5a4a2020-06-09 16:49:54 +100036using ::chromeos::machine_learning::mojom::HandwritingRecognizerSpec;
37using ::chromeos::machine_learning::mojom::HandwritingRecognizerSpecPtr;
Michael Martisa74af932018-08-13 16:52:36 +100038using ::chromeos::machine_learning::mojom::LoadModelResult;
Michael Martisa74af932018-08-13 16:52:36 +100039using ::chromeos::machine_learning::mojom::ModelRequest;
Michael Martisa74af932018-08-13 16:52:36 +100040
41constexpr char kSystemModelDir[] = "/opt/google/chrome/ml_models/";
Andrew Moylan79b34a42020-07-08 11:13:11 +100042// Base name for UMA metrics related to model loading (`LoadBuiltinModel`,
43// `LoadFlatBufferModel`, `LoadTextClassifier` or LoadHandwritingModel).
Honglin Yu6adafcd2019-07-22 13:48:11 +100044constexpr char kMetricsRequestName[] = "LoadModelResult";
Michael Martisa74af932018-08-13 16:52:36 +100045
Honglin Yuf33dce32019-12-05 15:10:39 +110046constexpr char kTextClassifierModelFile[] =
47 "mlservice-model-text_classifier_en-v706.fb";
48
49constexpr char kIcuDataFilePath[] = "/opt/google/chrome/icudtl.dat";
50
Michael Martisa74af932018-08-13 16:52:36 +100051} // namespace
52
Andrew Moylanff6be512018-07-03 11:05:01 +100053MachineLearningServiceImpl::MachineLearningServiceImpl(
Michael Martisa74af932018-08-13 16:52:36 +100054 mojo::ScopedMessagePipeHandle pipe,
55 base::Closure connection_error_handler,
56 const std::string& model_dir)
Honglin Yuf33dce32019-12-05 15:10:39 +110057 : icu_data_(nullptr),
58 text_classifier_model_filename_(kTextClassifierModelFile),
59 builtin_model_metadata_(GetBuiltinModelMetadata()),
Michael Martisa74af932018-08-13 16:52:36 +100060 model_dir_(model_dir),
hscham68867652020-01-06 11:40:47 +090061 binding_(this,
62 mojo::InterfaceRequest<
63 chromeos::machine_learning::mojom::MachineLearningService>(
Honglin Yuf33dce32019-12-05 15:10:39 +110064 std::move(pipe))) {
Andrew Moylanff6be512018-07-03 11:05:01 +100065 binding_.set_connection_error_handler(std::move(connection_error_handler));
66}
67
Michael Martisa74af932018-08-13 16:52:36 +100068MachineLearningServiceImpl::MachineLearningServiceImpl(
69 mojo::ScopedMessagePipeHandle pipe, base::Closure connection_error_handler)
70 : MachineLearningServiceImpl(std::move(pipe),
71 std::move(connection_error_handler),
72 kSystemModelDir) {}
73
Honglin Yuf33dce32019-12-05 15:10:39 +110074void MachineLearningServiceImpl::SetTextClassifierModelFilenameForTesting(
75 const std::string& filename) {
76 text_classifier_model_filename_ = filename;
77}
78
Honglin Yu0ed72352019-08-27 17:42:01 +100079void MachineLearningServiceImpl::LoadBuiltinModel(
80 BuiltinModelSpecPtr spec,
81 ModelRequest request,
Qijiang Fan5d381a02020-04-19 23:42:37 +090082 LoadBuiltinModelCallback callback) {
Honglin Yu0ed72352019-08-27 17:42:01 +100083 // Unsupported models do not have metadata entries.
84 const auto metadata_lookup = builtin_model_metadata_.find(spec->id);
85 if (metadata_lookup == builtin_model_metadata_.end()) {
Honglin Yua81145a2019-09-23 15:20:13 +100086 LOG(WARNING) << "LoadBuiltinModel requested for unsupported model ID "
87 << spec->id << ".";
Qijiang Fan5d381a02020-04-19 23:42:37 +090088 std::move(callback).Run(LoadModelResult::MODEL_SPEC_ERROR);
Honglin Yu0ed72352019-08-27 17:42:01 +100089 RecordModelSpecificationErrorEvent();
90 return;
91 }
92
93 const BuiltinModelMetadata& metadata = metadata_lookup->second;
94
95 DCHECK(!metadata.metrics_model_name.empty());
96
97 RequestMetrics<LoadModelResult> request_metrics(metadata.metrics_model_name,
98 kMetricsRequestName);
99 request_metrics.StartRecordingPerformanceMetrics();
100
101 // Attempt to load model.
102 const std::string model_path = model_dir_ + metadata.model_file;
103 std::unique_ptr<tflite::FlatBufferModel> model =
104 tflite::FlatBufferModel::BuildFromFile(model_path.c_str());
105 if (model == nullptr) {
106 LOG(ERROR) << "Failed to load model file '" << model_path << "'.";
Qijiang Fan5d381a02020-04-19 23:42:37 +0900107 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
Honglin Yu0ed72352019-08-27 17:42:01 +1000108 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
109 return;
110 }
111
Honglin Yuc0cef102020-01-17 15:26:01 +1100112 ModelImpl::Create(metadata.required_inputs, metadata.required_outputs,
113 std::move(model), std::move(request),
114 metadata.metrics_model_name);
Honglin Yu0ed72352019-08-27 17:42:01 +1000115
Qijiang Fan5d381a02020-04-19 23:42:37 +0900116 std::move(callback).Run(LoadModelResult::OK);
Honglin Yu0ed72352019-08-27 17:42:01 +1000117
118 request_metrics.FinishRecordingPerformanceMetrics();
119 request_metrics.RecordRequestEvent(LoadModelResult::OK);
120}
121
122void MachineLearningServiceImpl::LoadFlatBufferModel(
123 FlatBufferModelSpecPtr spec,
124 ModelRequest request,
Qijiang Fan5d381a02020-04-19 23:42:37 +0900125 LoadFlatBufferModelCallback callback) {
Honglin Yu0ed72352019-08-27 17:42:01 +1000126 DCHECK(!spec->metrics_model_name.empty());
127
128 RequestMetrics<LoadModelResult> request_metrics(spec->metrics_model_name,
129 kMetricsRequestName);
130 request_metrics.StartRecordingPerformanceMetrics();
131
Andrew Moylan79b34a42020-07-08 11:13:11 +1000132 // Take the ownership of the content of `model_string` because `ModelImpl` has
Honglin Yu0ed72352019-08-27 17:42:01 +1000133 // to hold the memory.
134 auto model_string_impl =
135 std::make_unique<std::string>(std::move(spec->model_string));
136
137 std::unique_ptr<tflite::FlatBufferModel> model =
138 tflite::FlatBufferModel::BuildFromBuffer(model_string_impl->c_str(),
139 model_string_impl->length());
140 if (model == nullptr) {
141 LOG(ERROR) << "Failed to load model string of metric name: "
142 << spec->metrics_model_name << "'.";
Qijiang Fan5d381a02020-04-19 23:42:37 +0900143 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
Honglin Yu0ed72352019-08-27 17:42:01 +1000144 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
145 return;
146 }
147
Honglin Yuc0cef102020-01-17 15:26:01 +1100148 ModelImpl::Create(
Honglin Yu0ed72352019-08-27 17:42:01 +1000149 std::map<std::string, int>(spec->inputs.begin(), spec->inputs.end()),
150 std::map<std::string, int>(spec->outputs.begin(), spec->outputs.end()),
151 std::move(model), std::move(model_string_impl), std::move(request),
152 spec->metrics_model_name);
153
Qijiang Fan5d381a02020-04-19 23:42:37 +0900154 std::move(callback).Run(LoadModelResult::OK);
Honglin Yu0ed72352019-08-27 17:42:01 +1000155
156 request_metrics.FinishRecordingPerformanceMetrics();
157 request_metrics.RecordRequestEvent(LoadModelResult::OK);
158}
159
Honglin Yuf33dce32019-12-05 15:10:39 +1100160void MachineLearningServiceImpl::LoadTextClassifier(
161 chromeos::machine_learning::mojom::TextClassifierRequest request,
162 LoadTextClassifierCallback callback) {
163 RequestMetrics<LoadModelResult> request_metrics("TextClassifier",
164 kMetricsRequestName);
165 request_metrics.StartRecordingPerformanceMetrics();
166
167 // Attempt to load model.
168 std::string model_path = model_dir_ + text_classifier_model_filename_;
169 auto scoped_mmap =
170 std::make_unique<libtextclassifier3::ScopedMmap>(model_path);
171 if (!scoped_mmap->handle().ok()) {
172 LOG(ERROR) << "Failed to load the text classifier model file '"
173 << model_path << "'.";
174 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
175 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
176 return;
177 }
178
179 // Create the TextClassifier.
180 if (!TextClassifierImpl::Create(&scoped_mmap, std::move(request))) {
181 LOG(ERROR) << "Failed to create TextClassifierImpl object.";
182 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
183 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
184 return;
185 }
186
187 // initialize the icu library.
188 InitIcuIfNeeded();
189
190 std::move(callback).Run(LoadModelResult::OK);
191
192 request_metrics.FinishRecordingPerformanceMetrics();
193 request_metrics.RecordRequestEvent(LoadModelResult::OK);
194}
195
charleszhao17777f92020-04-23 12:53:11 +1000196void MachineLearningServiceImpl::LoadHandwritingModel(
197 HandwritingRecognizerRequest request,
198 LoadHandwritingModelCallback callback) {
charleszhao05c5a4a2020-06-09 16:49:54 +1000199 // Use english as default language.
200 LoadHandwritingModelWithSpec(HandwritingRecognizerSpec::New("en"),
201 std::move(request), std::move(callback));
202}
203
204void MachineLearningServiceImpl::LoadHandwritingModelWithSpec(
205 HandwritingRecognizerSpecPtr spec,
206 HandwritingRecognizerRequest request,
207 LoadHandwritingModelCallback callback) {
charleszhao17777f92020-04-23 12:53:11 +1000208 RequestMetrics<LoadModelResult> request_metrics("HandwritingModel",
209 kMetricsRequestName);
210 request_metrics.StartRecordingPerformanceMetrics();
211
212 // Load HandwritingLibrary.
213 auto* const hwr_library = ml::HandwritingLibrary::GetInstance();
214
215 if (hwr_library->GetStatus() ==
216 ml::HandwritingLibrary::Status::kNotSupported) {
217 LOG(ERROR) << "Initialize ml::HandwritingLibrary with error "
218 << static_cast<int>(hwr_library->GetStatus());
219
220 std::move(callback).Run(LoadModelResult::FEATURE_NOT_SUPPORTED_ERROR);
221 request_metrics.RecordRequestEvent(
222 LoadModelResult::FEATURE_NOT_SUPPORTED_ERROR);
223 return;
224 }
225
226 if (hwr_library->GetStatus() != ml::HandwritingLibrary::Status::kOk) {
227 LOG(ERROR) << "Initialize ml::HandwritingLibrary with error "
228 << static_cast<int>(hwr_library->GetStatus());
229
230 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
231 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
232 return;
233 }
234
charleszhao05c5a4a2020-06-09 16:49:54 +1000235 if (!GetModelPaths(spec.Clone()).has_value()) {
236 LOG(ERROR) << "LoadHandwritingRecognizer is not called because language "
237 "code is not supported.";
238
239 std::move(callback).Run(LoadModelResult::LANGUAGE_NOT_SUPPORTED_ERROR);
240 request_metrics.RecordRequestEvent(
241 LoadModelResult::LANGUAGE_NOT_SUPPORTED_ERROR);
242 return;
243 }
244
charleszhao17777f92020-04-23 12:53:11 +1000245 // Create HandwritingRecognizer.
charleszhao05c5a4a2020-06-09 16:49:54 +1000246 if (!HandwritingRecognizerImpl::Create(std::move(spec), std::move(request))) {
charleszhao17777f92020-04-23 12:53:11 +1000247 LOG(ERROR) << "LoadHandwritingRecognizer returned false.";
248 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
249 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
250 return;
251 }
252
253 std::move(callback).Run(LoadModelResult::OK);
254 request_metrics.FinishRecordingPerformanceMetrics();
255 request_metrics.RecordRequestEvent(LoadModelResult::OK);
256}
257
Honglin Yuf33dce32019-12-05 15:10:39 +1100258void MachineLearningServiceImpl::InitIcuIfNeeded() {
259 if (icu_data_ == nullptr) {
260 // Need to load the data file again.
261 int64_t file_size;
262 const base::FilePath icu_data_file_path(kIcuDataFilePath);
263 CHECK(base::GetFileSize(icu_data_file_path, &file_size));
264 icu_data_ = new char[file_size];
265 CHECK(base::ReadFile(icu_data_file_path, icu_data_,
266 static_cast<int>(file_size)) == file_size);
267 // Init the Icu library.
268 UErrorCode err = U_ZERO_ERROR;
269 udata_setCommonData(reinterpret_cast<void*>(icu_data_), &err);
270 DCHECK(err == U_ZERO_ERROR);
271 // Never try to load Icu data from files.
272 udata_setFileAccess(UDATA_ONLY_PACKAGES, &err);
273 }
274}
275
Andrew Moylanff6be512018-07-03 11:05:01 +1000276} // namespace ml