• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #include "tensorflow_lite_support/cc/task/text/nlclassifier/bert_nl_classifier_c_api.h"
17 
18 #include <memory>
19 
20 #include "absl/strings/string_view.h"
21 #include "tensorflow_lite_support/cc/task/core/category.h"
22 #include "tensorflow_lite_support/cc/task/text/nlclassifier/bert_nl_classifier.h"
23 
24 using CategoryCPP = ::tflite::task::core::Category;
25 using BertNLClassifierCPP =
26     ::tflite::task::text::nlclassifier::BertNLClassifier;
27 
28 #ifdef __cplusplus
29 extern "C" {
30 #endif  // __cplusplus
31 
32 struct BertNLClassifier {
33   std::unique_ptr<BertNLClassifierCPP> impl;
34 };
35 
BertNLClassifierFromFile(const char * model_path)36 BertNLClassifier* BertNLClassifierFromFile(const char* model_path) {
37   auto classifier_status =
38       BertNLClassifierCPP::CreateFromFile(std::string(model_path));
39   if (classifier_status.ok()) {
40     return new BertNLClassifier{.impl = std::unique_ptr<BertNLClassifierCPP>(
41                                     dynamic_cast<BertNLClassifierCPP*>(
42                                         classifier_status.value().release()))};
43   } else {
44     return nullptr;
45   }
46 }
47 
BertNLClassifierClassify(const BertNLClassifier * classifier,const char * text)48 Categories* BertNLClassifierClassify(const BertNLClassifier* classifier,
49                                      const char* text) {
50   std::vector<CategoryCPP> results =
51       classifier->impl->Classify(absl::string_view(text).data());
52   size_t size = results.size();
53   auto* categories = new Category[size];
54 
55   for (size_t i = 0; i < size; ++i) {
56     categories[i].text = strdup(results[i].class_name.c_str());
57     categories[i].score = results[i].score;
58   }
59 
60   auto* c_categories = new Categories;
61   c_categories->size = size;
62   c_categories->categories = categories;
63   return c_categories;
64 }
65 
BertNLClassifierDelete(BertNLClassifier * classifier)66 void BertNLClassifierDelete(BertNLClassifier* classifier) { delete classifier; }
67 
68 #ifdef __cplusplus
69 }  // extern "C"
70 #endif  // __cplusplus
71