blob: 86fc323882de2be61c6acf7b4c5a9292540a4c48 [file] [log] [blame]
Jing Wang961b8af2020-10-26 12:40:35 +11001// Copyright 2020 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/grammar_checker_impl.h"
6
7#include <utility>
8#include <vector>
9
10#include "ml/grammar_proto_mojom_conversion.h"
11#include "ml/request_metrics.h"
12
Qijiang Fan713061e2021-03-08 15:45:12 +090013#include <base/check.h>
14
Jing Wang961b8af2020-10-26 12:40:35 +110015namespace ml {
16namespace {
17
18using ::chromeos::machine_learning::mojom::GrammarChecker;
19using ::chromeos::machine_learning::mojom::GrammarCheckerCandidatePtr;
20using ::chromeos::machine_learning::mojom::GrammarCheckerQueryPtr;
21using ::chromeos::machine_learning::mojom::GrammarCheckerResult;
22
23} // namespace
24
25bool GrammarCheckerImpl::Create(
26 mojo::PendingReceiver<GrammarChecker> receiver) {
27 auto checker_impl = new GrammarCheckerImpl(std::move(receiver));
28
29 // Set the disconnection handler to strongly bind `checker_impl` to delete
30 // `checker_impl` when the connection is gone.
31 checker_impl->receiver_.set_disconnect_handler(base::Bind(
32 [](const GrammarCheckerImpl* const checker_impl) { delete checker_impl; },
33 base::Unretained(checker_impl)));
34
35 return checker_impl->successfully_loaded_;
36}
37
38GrammarCheckerImpl::GrammarCheckerImpl(
39 mojo::PendingReceiver<GrammarChecker> receiver)
40 : library_(ml::GrammarLibrary::GetInstance()),
41 receiver_(this, std::move(receiver)) {
42 DCHECK(library_->GetStatus() == ml::GrammarLibrary::Status::kOk)
43 << "GrammarCheckerImpl should be created only if GrammarLibrary is "
44 "initialized successfully.";
45
46 checker_ = library_->CreateGrammarChecker();
47
48 successfully_loaded_ = library_->LoadGrammarChecker(checker_);
49}
50
51GrammarCheckerImpl::~GrammarCheckerImpl() {
52 library_->DestroyGrammarChecker(checker_);
53}
54
55void GrammarCheckerImpl::Check(GrammarCheckerQueryPtr query,
56 CheckCallback callback) {
57 RequestMetrics request_metrics("GrammarChecker", "Check");
58 request_metrics.StartRecordingPerformanceMetrics();
59
60 chrome_knowledge::GrammarCheckerResult result_proto;
61
62 if (library_->CheckGrammar(checker_,
63 GrammarCheckerQueryToProto(std::move(query)),
64 &result_proto)) {
65 // Check succeeded, run callback on the result.
66 std::move(callback).Run(GrammarCheckerResultFromProto(result_proto));
67 request_metrics.FinishRecordingPerformanceMetrics();
68 request_metrics.RecordRequestEvent(GrammarCheckerResult::Status::OK);
69 } else {
70 // Check failed, run callback on empty result and status = ERROR.
71 std::move(callback).Run(
72 GrammarCheckerResult::New(GrammarCheckerResult::Status::ERROR,
73 std::vector<GrammarCheckerCandidatePtr>()));
74 request_metrics.RecordRequestEvent(GrammarCheckerResult::Status::ERROR);
75 }
76}
77
78} // namespace ml