blob: 13c50d28076a171974f0f0e67a8d7b21bfe44e11 [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"
21#include "ml/handwriting_recognizer_impl.h"
Michael Martisa74af932018-08-13 16:52:36 +100022#include "ml/model_impl.h"
charleszhao17777f92020-04-23 12:53:11 +100023#include "ml/mojom/handwriting_recognizer.mojom.h"
Hidehiko Abeaa488c32018-08-31 23:49:41 +090024#include "ml/mojom/model.mojom.h"
Honglin Yuf33dce32019-12-05 15:10:39 +110025#include "ml/text_classifier_impl.h"
Michael Martisa74af932018-08-13 16:52:36 +100026
Andrew Moylanff6be512018-07-03 11:05:01 +100027namespace ml {
28
Michael Martisa74af932018-08-13 16:52:36 +100029namespace {
30
Honglin Yu0ed72352019-08-27 17:42:01 +100031using ::chromeos::machine_learning::mojom::BuiltinModelId;
32using ::chromeos::machine_learning::mojom::BuiltinModelSpecPtr;
33using ::chromeos::machine_learning::mojom::FlatBufferModelSpecPtr;
Andrew Moylanb481af72020-07-09 15:22:00 +100034using ::chromeos::machine_learning::mojom::HandwritingRecognizer;
charleszhao05c5a4a2020-06-09 16:49:54 +100035using ::chromeos::machine_learning::mojom::HandwritingRecognizerSpec;
36using ::chromeos::machine_learning::mojom::HandwritingRecognizerSpecPtr;
Michael Martisa74af932018-08-13 16:52:36 +100037using ::chromeos::machine_learning::mojom::LoadModelResult;
Andrew Moylanb481af72020-07-09 15:22:00 +100038using ::chromeos::machine_learning::mojom::MachineLearningService;
39using ::chromeos::machine_learning::mojom::Model;
40using ::chromeos::machine_learning::mojom::TextClassifier;
Michael Martisa74af932018-08-13 16:52:36 +100041
42constexpr char kSystemModelDir[] = "/opt/google/chrome/ml_models/";
Andrew Moylan79b34a42020-07-08 11:13:11 +100043// Base name for UMA metrics related to model loading (`LoadBuiltinModel`,
44// `LoadFlatBufferModel`, `LoadTextClassifier` or LoadHandwritingModel).
Honglin Yu6adafcd2019-07-22 13:48:11 +100045constexpr char kMetricsRequestName[] = "LoadModelResult";
Michael Martisa74af932018-08-13 16:52:36 +100046
Honglin Yuf33dce32019-12-05 15:10:39 +110047constexpr char kTextClassifierModelFile[] =
48 "mlservice-model-text_classifier_en-v706.fb";
49
Honglin Yuc5100022020-07-09 11:54:27 +100050constexpr char kLanguageIdentificationModelFile[] =
51 "mlservice-model-language_identification-20190924.smfb";
52
Honglin Yuf33dce32019-12-05 15:10:39 +110053constexpr char kIcuDataFilePath[] = "/opt/google/chrome/icudtl.dat";
54
Michael Martisa74af932018-08-13 16:52:36 +100055} // namespace
56
Andrew Moylanff6be512018-07-03 11:05:01 +100057MachineLearningServiceImpl::MachineLearningServiceImpl(
Michael Martisa74af932018-08-13 16:52:36 +100058 mojo::ScopedMessagePipeHandle pipe,
Andrew Moylanb481af72020-07-09 15:22:00 +100059 base::Closure disconnect_handler,
Michael Martisa74af932018-08-13 16:52:36 +100060 const std::string& model_dir)
Honglin Yuf33dce32019-12-05 15:10:39 +110061 : icu_data_(nullptr),
62 text_classifier_model_filename_(kTextClassifierModelFile),
63 builtin_model_metadata_(GetBuiltinModelMetadata()),
Michael Martisa74af932018-08-13 16:52:36 +100064 model_dir_(model_dir),
Andrew Moylanb481af72020-07-09 15:22:00 +100065 receiver_(this,
66 mojo::InterfaceRequest<
67 chromeos::machine_learning::mojom::MachineLearningService>(
68 std::move(pipe))) {
69 receiver_.set_disconnect_handler(std::move(disconnect_handler));
Andrew Moylanff6be512018-07-03 11:05:01 +100070}
71
Michael Martisa74af932018-08-13 16:52:36 +100072MachineLearningServiceImpl::MachineLearningServiceImpl(
Andrew Moylanb481af72020-07-09 15:22:00 +100073 mojo::ScopedMessagePipeHandle pipe, base::Closure disconnect_handler)
74 : MachineLearningServiceImpl(
75 std::move(pipe), std::move(disconnect_handler), kSystemModelDir) {}
Michael Martisa74af932018-08-13 16:52:36 +100076
Honglin Yuf33dce32019-12-05 15:10:39 +110077void MachineLearningServiceImpl::SetTextClassifierModelFilenameForTesting(
78 const std::string& filename) {
79 text_classifier_model_filename_ = filename;
80}
81
Andrew Moylanb481af72020-07-09 15:22:00 +100082void MachineLearningServiceImpl::Clone(
83 mojo::PendingReceiver<MachineLearningService> receiver) {
84 clone_receivers_.Add(this, std::move(receiver));
Andrew Moylan2fb80af2020-07-08 10:52:08 +100085}
86
Honglin Yu0ed72352019-08-27 17:42:01 +100087void MachineLearningServiceImpl::LoadBuiltinModel(
88 BuiltinModelSpecPtr spec,
Andrew Moylanb481af72020-07-09 15:22:00 +100089 mojo::PendingReceiver<Model> receiver,
Qijiang Fan5d381a02020-04-19 23:42:37 +090090 LoadBuiltinModelCallback callback) {
Honglin Yu0ed72352019-08-27 17:42:01 +100091 // Unsupported models do not have metadata entries.
92 const auto metadata_lookup = builtin_model_metadata_.find(spec->id);
93 if (metadata_lookup == builtin_model_metadata_.end()) {
Honglin Yua81145a2019-09-23 15:20:13 +100094 LOG(WARNING) << "LoadBuiltinModel requested for unsupported model ID "
95 << spec->id << ".";
Qijiang Fan5d381a02020-04-19 23:42:37 +090096 std::move(callback).Run(LoadModelResult::MODEL_SPEC_ERROR);
Honglin Yu0ed72352019-08-27 17:42:01 +100097 RecordModelSpecificationErrorEvent();
98 return;
99 }
100
101 const BuiltinModelMetadata& metadata = metadata_lookup->second;
102
103 DCHECK(!metadata.metrics_model_name.empty());
104
charleszhao5a7050e2020-07-14 15:21:41 +1000105 RequestMetrics request_metrics(metadata.metrics_model_name,
106 kMetricsRequestName);
Honglin Yu0ed72352019-08-27 17:42:01 +1000107 request_metrics.StartRecordingPerformanceMetrics();
108
109 // Attempt to load model.
110 const std::string model_path = model_dir_ + metadata.model_file;
111 std::unique_ptr<tflite::FlatBufferModel> model =
112 tflite::FlatBufferModel::BuildFromFile(model_path.c_str());
113 if (model == nullptr) {
114 LOG(ERROR) << "Failed to load model file '" << model_path << "'.";
Qijiang Fan5d381a02020-04-19 23:42:37 +0900115 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
Honglin Yu0ed72352019-08-27 17:42:01 +1000116 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
117 return;
118 }
119
Honglin Yuc0cef102020-01-17 15:26:01 +1100120 ModelImpl::Create(metadata.required_inputs, metadata.required_outputs,
Andrew Moylanb481af72020-07-09 15:22:00 +1000121 std::move(model), std::move(receiver),
Honglin Yuc0cef102020-01-17 15:26:01 +1100122 metadata.metrics_model_name);
Honglin Yu0ed72352019-08-27 17:42:01 +1000123
Qijiang Fan5d381a02020-04-19 23:42:37 +0900124 std::move(callback).Run(LoadModelResult::OK);
Honglin Yu0ed72352019-08-27 17:42:01 +1000125
126 request_metrics.FinishRecordingPerformanceMetrics();
127 request_metrics.RecordRequestEvent(LoadModelResult::OK);
128}
129
130void MachineLearningServiceImpl::LoadFlatBufferModel(
131 FlatBufferModelSpecPtr spec,
Andrew Moylanb481af72020-07-09 15:22:00 +1000132 mojo::PendingReceiver<Model> receiver,
Qijiang Fan5d381a02020-04-19 23:42:37 +0900133 LoadFlatBufferModelCallback callback) {
Honglin Yu0ed72352019-08-27 17:42:01 +1000134 DCHECK(!spec->metrics_model_name.empty());
135
charleszhao5a7050e2020-07-14 15:21:41 +1000136 RequestMetrics request_metrics(spec->metrics_model_name, kMetricsRequestName);
Honglin Yu0ed72352019-08-27 17:42:01 +1000137 request_metrics.StartRecordingPerformanceMetrics();
138
Andrew Moylan79b34a42020-07-08 11:13:11 +1000139 // Take the ownership of the content of `model_string` because `ModelImpl` has
Honglin Yu0ed72352019-08-27 17:42:01 +1000140 // to hold the memory.
141 auto model_string_impl =
142 std::make_unique<std::string>(std::move(spec->model_string));
143
144 std::unique_ptr<tflite::FlatBufferModel> model =
145 tflite::FlatBufferModel::BuildFromBuffer(model_string_impl->c_str(),
146 model_string_impl->length());
147 if (model == nullptr) {
148 LOG(ERROR) << "Failed to load model string of metric name: "
149 << spec->metrics_model_name << "'.";
Qijiang Fan5d381a02020-04-19 23:42:37 +0900150 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
Honglin Yu0ed72352019-08-27 17:42:01 +1000151 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
152 return;
153 }
154
Honglin Yuc0cef102020-01-17 15:26:01 +1100155 ModelImpl::Create(
Honglin Yu0ed72352019-08-27 17:42:01 +1000156 std::map<std::string, int>(spec->inputs.begin(), spec->inputs.end()),
157 std::map<std::string, int>(spec->outputs.begin(), spec->outputs.end()),
Andrew Moylanb481af72020-07-09 15:22:00 +1000158 std::move(model), std::move(model_string_impl), std::move(receiver),
Honglin Yu0ed72352019-08-27 17:42:01 +1000159 spec->metrics_model_name);
160
Qijiang Fan5d381a02020-04-19 23:42:37 +0900161 std::move(callback).Run(LoadModelResult::OK);
Honglin Yu0ed72352019-08-27 17:42:01 +1000162
163 request_metrics.FinishRecordingPerformanceMetrics();
164 request_metrics.RecordRequestEvent(LoadModelResult::OK);
165}
166
Honglin Yuf33dce32019-12-05 15:10:39 +1100167void MachineLearningServiceImpl::LoadTextClassifier(
Andrew Moylanb481af72020-07-09 15:22:00 +1000168 mojo::PendingReceiver<TextClassifier> receiver,
Honglin Yuf33dce32019-12-05 15:10:39 +1100169 LoadTextClassifierCallback callback) {
charleszhao5a7050e2020-07-14 15:21:41 +1000170 RequestMetrics request_metrics("TextClassifier", kMetricsRequestName);
Honglin Yuf33dce32019-12-05 15:10:39 +1100171 request_metrics.StartRecordingPerformanceMetrics();
172
173 // Attempt to load model.
174 std::string model_path = model_dir_ + text_classifier_model_filename_;
175 auto scoped_mmap =
176 std::make_unique<libtextclassifier3::ScopedMmap>(model_path);
177 if (!scoped_mmap->handle().ok()) {
178 LOG(ERROR) << "Failed to load the text classifier model file '"
179 << model_path << "'.";
180 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
181 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
182 return;
183 }
184
185 // Create the TextClassifier.
Honglin Yuc5100022020-07-09 11:54:27 +1000186 if (!TextClassifierImpl::Create(&scoped_mmap,
187 model_dir_ + kLanguageIdentificationModelFile,
Andrew Moylanb481af72020-07-09 15:22:00 +1000188 std::move(receiver))) {
Honglin Yuf33dce32019-12-05 15:10:39 +1100189 LOG(ERROR) << "Failed to create TextClassifierImpl object.";
190 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
191 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
192 return;
193 }
194
195 // initialize the icu library.
196 InitIcuIfNeeded();
197
198 std::move(callback).Run(LoadModelResult::OK);
199
200 request_metrics.FinishRecordingPerformanceMetrics();
201 request_metrics.RecordRequestEvent(LoadModelResult::OK);
202}
203
Charles Zhaoc882eb02020-07-27 10:02:35 +1000204void MachineLearningServiceImpl::RemovedFunction_3() {
205 NOTREACHED() << "RemovedFunction_3 should not be called";
charleszhao05c5a4a2020-06-09 16:49:54 +1000206}
207
208void MachineLearningServiceImpl::LoadHandwritingModelWithSpec(
209 HandwritingRecognizerSpecPtr spec,
Andrew Moylanb481af72020-07-09 15:22:00 +1000210 mojo::PendingReceiver<HandwritingRecognizer> receiver,
Charles Zhaoc882eb02020-07-27 10:02:35 +1000211 LoadHandwritingModelWithSpecCallback callback) {
charleszhao5a7050e2020-07-14 15:21:41 +1000212 RequestMetrics request_metrics("HandwritingModel", kMetricsRequestName);
charleszhao17777f92020-04-23 12:53:11 +1000213 request_metrics.StartRecordingPerformanceMetrics();
214
215 // Load HandwritingLibrary.
216 auto* const hwr_library = ml::HandwritingLibrary::GetInstance();
217
218 if (hwr_library->GetStatus() ==
219 ml::HandwritingLibrary::Status::kNotSupported) {
220 LOG(ERROR) << "Initialize ml::HandwritingLibrary with error "
221 << static_cast<int>(hwr_library->GetStatus());
222
223 std::move(callback).Run(LoadModelResult::FEATURE_NOT_SUPPORTED_ERROR);
224 request_metrics.RecordRequestEvent(
225 LoadModelResult::FEATURE_NOT_SUPPORTED_ERROR);
226 return;
227 }
228
229 if (hwr_library->GetStatus() != ml::HandwritingLibrary::Status::kOk) {
230 LOG(ERROR) << "Initialize ml::HandwritingLibrary with error "
231 << static_cast<int>(hwr_library->GetStatus());
232
233 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
234 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
235 return;
236 }
237
238 // Create HandwritingRecognizer.
Andrew Moylanb481af72020-07-09 15:22:00 +1000239 if (!HandwritingRecognizerImpl::Create(std::move(spec),
240 std::move(receiver))) {
charleszhao17777f92020-04-23 12:53:11 +1000241 LOG(ERROR) << "LoadHandwritingRecognizer returned false.";
242 std::move(callback).Run(LoadModelResult::LOAD_MODEL_ERROR);
243 request_metrics.RecordRequestEvent(LoadModelResult::LOAD_MODEL_ERROR);
244 return;
245 }
246
247 std::move(callback).Run(LoadModelResult::OK);
248 request_metrics.FinishRecordingPerformanceMetrics();
249 request_metrics.RecordRequestEvent(LoadModelResult::OK);
250}
251
Honglin Yuf33dce32019-12-05 15:10:39 +1100252void MachineLearningServiceImpl::InitIcuIfNeeded() {
253 if (icu_data_ == nullptr) {
254 // Need to load the data file again.
255 int64_t file_size;
256 const base::FilePath icu_data_file_path(kIcuDataFilePath);
257 CHECK(base::GetFileSize(icu_data_file_path, &file_size));
258 icu_data_ = new char[file_size];
259 CHECK(base::ReadFile(icu_data_file_path, icu_data_,
260 static_cast<int>(file_size)) == file_size);
261 // Init the Icu library.
262 UErrorCode err = U_ZERO_ERROR;
263 udata_setCommonData(reinterpret_cast<void*>(icu_data_), &err);
264 DCHECK(err == U_ZERO_ERROR);
265 // Never try to load Icu data from files.
266 udata_setFileAccess(UDATA_ONLY_PACKAGES, &err);
267 }
268}
269
Andrew Moylanff6be512018-07-03 11:05:01 +1000270} // namespace ml