write_json_op.cpp 2.3 KB
Newer Older
W
wangguibao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

W
wangguibao 已提交
15
#include <google/protobuf/text_format.h>
W
wangguibao 已提交
16 17
#include <string>
#include "json2pb/pb_to_json.h"
W
wangguibao 已提交
18 19

#include "framework/memory.h"
W
wangguibao 已提交
20
#include "op/write_json_op.h"
W
wangguibao 已提交
21 22 23 24 25 26 27 28 29 30

namespace baidu {
namespace paddle_serving {
namespace predictor {

using baidu::paddle_serving::predictor::format::XImageResInstance;
using baidu::paddle_serving::predictor::image_classification::ClassifyResponse;
using baidu::paddle_serving::predictor::image_classification::Response;

int WriteJsonOp::inference() {
W
wangguibao 已提交
31 32 33 34 35 36 37
  const ClassifyResponse* classify_out =
      get_depend_argument<ClassifyResponse>("image_classify_op");
  if (!classify_out) {
    LOG(ERROR) << "Failed mutable depended argument, op:"
               << "image_classify_op";
    return -1;
  }
W
wangguibao 已提交
38

W
wangguibao 已提交
39 40 41 42 43 44
  Response* res = mutable_data<Response>();
  if (!res) {
    LOG(ERROR) << "Failed mutable output response in op:"
               << "WriteJsonOp";
    return -1;
  }
W
wangguibao 已提交
45

W
wangguibao 已提交
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
  // transfer classify output message into json format
  std::string err_string;
  uint32_t sample_size = classify_out->predictions_size();
  for (uint32_t si = 0; si < sample_size; si++) {
    XImageResInstance* ins = res->add_predictions();
    if (!ins) {
      LOG(ERROR) << "Failed add one prediction ins";
      return -1;
    }
    std::string* text = ins->mutable_response_json();
    if (!json2pb::ProtoMessageToJson(
            classify_out->predictions(si), text, &err_string)) {
      LOG(ERROR) << "Failed convert message["
                 << classify_out->predictions(si).ShortDebugString()
                 << "], err: " << err_string;
      return -1;
W
wangguibao 已提交
62
    }
W
wangguibao 已提交
63
  }
W
wangguibao 已提交
64

W
wangguibao 已提交
65
  LOG(INFO) << "Succ write json:" << classify_out->ShortDebugString();
W
wangguibao 已提交
66

W
wangguibao 已提交
67
  return 0;
W
wangguibao 已提交
68 69 70 71
}

DEFINE_OP(WriteJsonOp);

W
wangguibao 已提交
72 73 74
}  // namespace predictor
}  // namespace paddle_serving
}  // namespace baidu