TensorFlow Serving C++ API Documentation
hashmap_source_adapter.cc
1 /* Copyright 2016 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 #include "tensorflow_serving/servables/hashmap/hashmap_source_adapter.h"
17 
18 #include <stddef.h>
19 
20 #include <memory>
21 #include <unordered_map>
22 #include <vector>
23 
24 #include "tensorflow/core/lib/core/errors.h"
25 #include "tensorflow/core/lib/core/status.h"
26 #include "tensorflow/core/lib/io/inputbuffer.h"
27 #include "tensorflow/core/lib/strings/str_util.h"
28 #include "tensorflow/core/platform/env.h"
29 #include "tensorflow/core/platform/types.h"
30 
31 namespace tensorflow {
32 namespace serving {
33 namespace {
34 
35 using Hashmap = std::unordered_map<string, string>;
36 
37 // Populates a hashmap from a file located at 'path', in format 'format'.
38 Status LoadHashmapFromFile(const string& path,
39  const HashmapSourceAdapterConfig::Format& format,
40  std::unique_ptr<Hashmap>* hashmap) {
41  hashmap->reset(new Hashmap);
42  switch (format) {
43  case HashmapSourceAdapterConfig::SIMPLE_CSV: {
44  std::unique_ptr<RandomAccessFile> file;
45  TF_RETURN_IF_ERROR(Env::Default()->NewRandomAccessFile(path, &file));
46  const size_t kBufferSizeBytes = 262144;
47  io::InputBuffer in(file.get(), kBufferSizeBytes);
48  string line;
49  while (in.ReadLine(&line).ok()) {
50  std::vector<string> cols = str_util::Split(line, ',');
51  if (cols.size() != 2) {
52  return errors::InvalidArgument("Unexpected format.");
53  }
54  const string& key = cols[0];
55  const string& value = cols[1];
56  (*hashmap)->insert({key, value});
57  }
58  break;
59  }
60  default:
61  return errors::InvalidArgument("Unrecognized format enum value: ",
62  format);
63  }
64  return Status();
65 }
66 
67 } // namespace
68 
69 HashmapSourceAdapter::HashmapSourceAdapter(
70  const HashmapSourceAdapterConfig& config)
71  : SimpleLoaderSourceAdapter<StoragePath, Hashmap>(
72  [config](const StoragePath& path, std::unique_ptr<Hashmap>* hashmap) {
73  return LoadHashmapFromFile(path, config.format(), hashmap);
74  },
75  // Decline to supply a resource footprint estimate.
76  SimpleLoaderSourceAdapter<StoragePath,
77  Hashmap>::EstimateNoResources()) {}
78 
79 HashmapSourceAdapter::~HashmapSourceAdapter() { Detach(); }
80 
81 } // namespace serving
82 } // namespace tensorflow