TensorFlow Serving C++ API Documentation
tflite_session_main.cc
1 /* Copyright 2019 Google Inc. 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 // Command line tool to create TF Lite Session from a TF Lite model file.
17 
18 #include <iostream>
19 #include <memory>
20 #include <string>
21 #include <utility>
22 
23 #include "tensorflow/core/platform/env.h"
24 #include "tensorflow/core/platform/init_main.h"
25 #include "tensorflow_serving/servables/tensorflow/tflite_session.h"
26 
27 int main(int argc, char** argv) {
28  if (argc != 2) {
29  std::cerr << "ERROR: Missing filename. Usage: " << argv[0]
30  << " <tflite-model-filename>" << std::endl;
31  return 1;
32  }
33 
34  tensorflow::port::InitMain(argv[0], &argc, &argv);
35 
36  const std::string filename(argv[1]);
37  std::string model_bytes;
38  auto status =
39  ReadFileToString(tensorflow::Env::Default(), filename, &model_bytes);
40  if (!status.ok()) {
41  std::cerr << "ERROR: Failed to read model file: " << filename
42  << " with error: " << status << std::endl;
43  return 1;
44  }
45 
46  ::google::protobuf::Map<std::string, tensorflow::SignatureDef> signatures;
47  std::unique_ptr<tensorflow::serving::TfLiteSession> session;
48  tensorflow::SessionOptions options;
49  status = tensorflow::serving::TfLiteSession::Create(
50  std::move(model_bytes), options, /*num_pools=*/1,
51  /*num_interpreters_per_pool=*/1, &session, &signatures);
52  if (!status.ok()) {
53  std::cerr << "ERROR: Failed to create TF Lite session with error: "
54  << status << std::endl;
55  return 1;
56  }
57  std::cout << "Successfully created TF Lite Session for model file: "
58  << filename << std::endl;
59 
60  std::cout << "Signatures: " << std::endl;
61  for (const auto& signature_info : signatures) {
62  std::cout << " " << signature_info.first << ": "
63  << signature_info.second.DebugString() << std::endl;
64  }
65  return 0;
66 }