• 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 <iostream>
17 #include "absl/strings/str_split.h"
18 #include "tensorflow/core/framework/op_kernel.h"
19 #include "tensorflow/core/lib/core/status.h"
20 #include "tensorflow/core/lib/strings/str_util.h"
21 #include "tensorflow/core/platform/logging.h"
22 
23 namespace tensorflow {
24 
25 class StringFormatOp : public OpKernel {
26  public:
StringFormatOp(OpKernelConstruction * ctx)27   explicit StringFormatOp(OpKernelConstruction* ctx) : OpKernel(ctx) {
28     string template_;
29     OP_REQUIRES_OK(ctx, ctx->GetAttr("template", &template_));
30     OP_REQUIRES_OK(ctx, ctx->GetAttr("placeholder", &placeholder_));
31     OP_REQUIRES_OK(ctx, ctx->GetAttr("summarize", &summarize_));
32 
33     split_template_ = absl::StrSplit(template_, placeholder_);
34     int64 num_placeholders = split_template_.size() - 1;
35     OP_REQUIRES(ctx, ctx->num_inputs() == num_placeholders,
36                 errors::InvalidArgument(strings::StrCat(
37                     "num placeholders in template and num inputs must match: ",
38                     num_placeholders, " vs. ", ctx->num_inputs())));
39   }
40 
Compute(OpKernelContext * ctx)41   void Compute(OpKernelContext* ctx) override {
42     Tensor* formatted_string = nullptr;
43     OP_REQUIRES_OK(ctx,
44                    ctx->allocate_output(0, TensorShape({}), &formatted_string));
45 
46     string msg;
47     strings::StrAppend(&msg, split_template_[0].c_str());
48     for (int i = 0; i < ctx->num_inputs(); ++i) {
49       strings::StrAppend(&msg, ctx->input(i).SummarizeValue(summarize_, true));
50       strings::StrAppend(&msg, split_template_[i + 1].c_str());
51     }
52 
53     formatted_string->scalar<string>()() = msg;
54   }
55 
56  private:
57   int32 summarize_ = 0;
58   string placeholder_;
59   std::vector<std::string> split_template_;
60 };
61 
62 REGISTER_KERNEL_BUILDER(Name("StringFormat").Device(DEVICE_CPU),
63                         StringFormatOp);
64 
65 }  // end namespace tensorflow
66