16 #include "tensorflow_serving/servables/hashmap/hashmap_source_adapter.h"
21 #include <unordered_map>
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"
31 namespace tensorflow {
35 using Hashmap = std::unordered_map<string, string>;
38 Status LoadHashmapFromFile(
const string& path,
39 const HashmapSourceAdapterConfig::Format& format,
40 std::unique_ptr<Hashmap>* hashmap) {
41 hashmap->reset(
new Hashmap);
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);
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.");
54 const string& key = cols[0];
55 const string& value = cols[1];
56 (*hashmap)->insert({key, value});
61 return errors::InvalidArgument(
"Unrecognized format enum value: ",
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);
76 SimpleLoaderSourceAdapter<StoragePath,
77 Hashmap>::EstimateNoResources()) {}
79 HashmapSourceAdapter::~HashmapSourceAdapter() { Detach(); }