• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2018 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/core/platform/human_readable_json.h"
17 
18 #include "tensorflow/core/platform/errors.h"
19 #include "tensorflow/core/platform/status.h"
20 #include "tensorflow/core/platform/strcat.h"
21 
22 namespace tensorflow {
23 
ProtoToHumanReadableJson(const protobuf::Message & proto,string * result,bool ignore_accuracy_loss)24 Status ProtoToHumanReadableJson(const protobuf::Message& proto, string* result,
25                                 bool ignore_accuracy_loss) {
26 #ifdef TENSORFLOW_LITE_PROTOS
27   *result = "[human readable output not available on Android]";
28   return Status::OK();
29 #else
30   result->clear();
31 
32   protobuf::util::JsonPrintOptions json_options;
33   json_options.preserve_proto_field_names = true;
34   json_options.always_print_primitive_fields = true;
35   auto status =
36       protobuf::util::MessageToJsonString(proto, result, json_options);
37   if (!status.ok()) {
38     // Convert error_msg google::protobuf::StringPiece to
39     // tensorflow::StringPiece.
40     auto error_msg = status.error_message();
41     return errors::Internal(
42         strings::StrCat("Could not convert proto to JSON string: ",
43                         StringPiece(error_msg.data(), error_msg.length())));
44   }
45   return Status::OK();
46 #endif
47 }
48 
HumanReadableJsonToProto(const string & str,protobuf::Message * proto)49 Status HumanReadableJsonToProto(const string& str, protobuf::Message* proto) {
50 #ifdef TENSORFLOW_LITE_PROTOS
51   return errors::Internal("Cannot parse JSON protos on Android");
52 #else
53   proto->Clear();
54   auto status = protobuf::util::JsonStringToMessage(str, proto);
55   if (!status.ok()) {
56     // Convert error_msg google::protobuf::StringPiece to
57     // tensorflow::StringPiece.
58     auto error_msg = status.error_message();
59     return errors::Internal(
60         strings::StrCat("Could not convert JSON string to proto: ",
61                         StringPiece(error_msg.data(), error_msg.length())));
62   }
63   return Status::OK();
64 #endif
65 }
66 
67 }  // namespace tensorflow
68