1 /* Copyright 2021 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 #include "tensorflow/cc/experimental/libexport/load.h"
16
17 #include "tensorflow/cc/saved_model/constants.h"
18 #include "tensorflow/core/framework/graph.pb.h"
19 #include "tensorflow/core/platform/env.h"
20 #include "tensorflow/core/platform/errors.h"
21 #include "tensorflow/core/platform/path.h"
22 #include "tensorflow/core/protobuf/meta_graph.pb.h"
23
24 #define RETURN_IF_ERROR(s) \
25 { \
26 auto c = (s); \
27 if (!c.ok()) return c; \
28 }
29
30 namespace tensorflow {
31 namespace libexport {
32
33 using protobuf::RepeatedPtrField;
34 using CheckpointKey = TFPackage::CheckpointKey;
35
Load(const std::string & path)36 tensorflow::StatusOr<TFPackage> TFPackage::Load(const std::string& path) {
37 // Load the proto
38 TFPackage tf_package;
39 const string saved_model_pb_path = io::JoinPath(path, kSavedModelFilenamePb);
40 const string saved_model_pbtxt_path =
41 io::JoinPath(path, kSavedModelFilenamePbTxt);
42 if (Env::Default()->FileExists(saved_model_pb_path).ok()) {
43 RETURN_IF_ERROR(ReadBinaryProto(Env::Default(), saved_model_pb_path,
44 &tf_package.saved_model_proto_));
45 } else if (Env::Default()->FileExists(saved_model_pbtxt_path).ok()) {
46 RETURN_IF_ERROR(ReadTextProto(Env::Default(), saved_model_pbtxt_path,
47 &tf_package.saved_model_proto_));
48 } else {
49 return Status(error::Code::NOT_FOUND,
50 "Could not find SavedModel .pb or .pbtxt at supplied export "
51 "directory path: " +
52 path);
53 }
54 return tf_package;
55 }
56
57 tensorflow::StatusOr<std::vector<CheckpointKey>>
GetVariableCheckpointKeys()58 TFPackage::GetVariableCheckpointKeys() {
59 return errors::Unimplemented("GetVariableCheckpointKeys not implemented.");
60 }
61
GetObjectGraph()62 const SavedObjectGraph& TFPackage::GetObjectGraph() {
63 return saved_model_proto_.mutable_meta_graphs(0)->object_graph_def();
64 }
65
GetFunctionDefs()66 const RepeatedPtrField<FunctionDef>& TFPackage::GetFunctionDefs() {
67 auto& function_library =
68 saved_model_proto_.mutable_meta_graphs(0)->graph_def().library();
69 return function_library.function();
70 }
71
72 } // namespace libexport
73 } // namespace tensorflow
74