| 50 | } |
| 51 | |
| 52 | void TFExtractTopLabels::onTrigger(const std::shared_ptr<core::ProcessContext> &context, |
| 53 | const std::shared_ptr<core::ProcessSession> &session) { |
| 54 | auto flow_file = session->get(); |
| 55 | |
| 56 | if (!flow_file) { |
| 57 | return; |
| 58 | } |
| 59 | |
| 60 | try { |
| 61 | |
| 62 | // Read labels |
| 63 | std::string tf_type; |
| 64 | flow_file->getAttribute("tf.type", tf_type); |
| 65 | std::shared_ptr<std::vector<std::string>> labels; |
| 66 | |
| 67 | { |
| 68 | std::lock_guard<std::mutex> guard(labels_mtx_); |
| 69 | |
| 70 | if (tf_type == "labels") { |
| 71 | logger_->log_info("Reading new labels..."); |
| 72 | auto new_labels = std::make_shared<std::vector<std::string>>(); |
| 73 | LabelsReadCallback cb(new_labels); |
| 74 | session->read(flow_file, &cb); |
| 75 | labels_ = new_labels; |
| 76 | logger_->log_info("Read %d new labels", labels_->size()); |
| 77 | session->remove(flow_file); |
| 78 | return; |
| 79 | } |
| 80 | |
| 81 | labels = labels_; |
| 82 | } |
| 83 | |
| 84 | // Read input tensor from flow file |
| 85 | auto input_tensor_proto = std::make_shared<tensorflow::TensorProto>(); |
| 86 | TensorReadCallback tensor_cb(input_tensor_proto); |
| 87 | session->read(flow_file, &tensor_cb); |
| 88 | |
| 89 | tensorflow::Tensor input; |
| 90 | input.FromProto(*input_tensor_proto); |
| 91 | auto input_flat = input.flat<float>(); |
| 92 | |
| 93 | std::vector<std::pair<uint64_t, float>> scores; |
| 94 | |
| 95 | for (int i = 0; i < input_flat.size(); i++) { |
| 96 | scores.emplace_back(std::make_pair(i, input_flat(i))); |
| 97 | } |
| 98 | |
| 99 | std::sort(scores.begin(), scores.end(), [](const std::pair<uint64_t, float> &a, |
| 100 | const std::pair<uint64_t, float> &b) { |
| 101 | return a.second > b.second; |
| 102 | }); |
| 103 | |
| 104 | for (int i = 0; i < 5 && i < scores.size(); i++) { |
| 105 | if (!labels || scores[i].first > labels->size()) { |
| 106 | logger_->log_error("Label index is out of range (are the correct labels loaded?); routing to retry..."); |
| 107 | session->transfer(flow_file, Retry); |
| 108 | return; |
| 109 | } |
nothing calls this directly
no test coverage detected