martinzink commented on code in PR #2258: URL: https://github.com/apache/nifi-minifi-cpp/pull/2258#discussion_r4105378396
########## minifi_rust/extensions/minifi_tensor/src/low_level_processors/classify_output.rs: ########## @@ -0,0 +1,476 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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 +// +// https://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. + +use crate::utils::score_activation::{ScoreActivation, SoftmaxTerms}; +use crate::utils::tensor_helpers::{deserialize_tensors, tensor_as_f32, tensor_shape}; +use classify_output_def::SUCCESS; +pub(crate) use classify_output_def::{ + CLASSIFY_OUTPUT_ATTRIBUTES, CONFIDENCE_THRESHOLD, LABEL_INDEX_OFFSET, LABELS_FILE_PATH, + OUTPUT_ATTRIBUTE_NAME, SCORE_ACTIVATION, SCORE_OUTPUT_INDEX, TOP_K, +}; +use minifi_native::macros::ComponentIdentifier; +use minifi_native::{ + Content, FlowFileTransform, GetAttribute, GetId, GetProperty, InputStream, Logger, MinifiError, + ProcessError, RouteErrorExt, Schedule, TransformedFlowFile, warn, +}; +use serde::Serialize; +use std::path::Path; +use tract::Tensor; + +mod classify_output_def; + +#[derive(Serialize, Clone, Debug, PartialEq)] +struct Prediction { + class_id: usize, + confidence: f32, + #[serde(skip_serializing_if = "Option::is_none")] + class_name: Option<String>, +} + +fn load_labels(path: &Path) -> Result<Vec<String>, MinifiError> { + let content = std::fs::read_to_string(path).map_err(|e| { + MinifiError::custom(format!("Failed to read labels file '{:?}': {}", path, e)) + })?; + Ok(content + .lines() + .map(|line| line.trim().to_string()) + .collect()) +} + +fn top_k(mut scored: Vec<(usize, f32)>, k: usize) -> Vec<(usize, f32)> { + scored.sort_by(|&(ai, a), &(bi, b)| b.total_cmp(&a).then(ai.cmp(&bi))); + scored.truncate(k); + scored +} + +#[derive(ComponentIdentifier)] +pub(crate) struct ClassifyOutput { + top_k: usize, + score_output_index: usize, + score_activation: ScoreActivation, + confidence_threshold: f32, + labels: Vec<String>, + label_index_offset: usize, +} + +impl Schedule for ClassifyOutput { + fn schedule<Ctx: GetProperty, L: Logger>( + context: &Ctx, + _logger: &L, + ) -> Result<Self, MinifiError> + where + Self: Sized, + { + let top_k = context.get_property(&TOP_K)?; + if top_k == 0 { + return Err(MinifiError::validation("Top K must be >= 1")); + } + let score_output_index = context.get_property(&SCORE_OUTPUT_INDEX)?; + let score_activation = context.get_property(&SCORE_ACTIVATION)?; + let confidence_threshold = context.get_property(&CONFIDENCE_THRESHOLD)?; + + let labels = match context.get_property(&LABELS_FILE_PATH)? { + Some(path) => load_labels(&path)?, + _ => Vec::new(), Review Comment: thats good idea, ########## minifi_rust/extensions/minifi_tensor/src/low_level_processors/classify_output.rs: ########## @@ -0,0 +1,476 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you 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 +// +// https://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. + +use crate::utils::score_activation::{ScoreActivation, SoftmaxTerms}; +use crate::utils::tensor_helpers::{deserialize_tensors, tensor_as_f32, tensor_shape}; +use classify_output_def::SUCCESS; +pub(crate) use classify_output_def::{ + CLASSIFY_OUTPUT_ATTRIBUTES, CONFIDENCE_THRESHOLD, LABEL_INDEX_OFFSET, LABELS_FILE_PATH, + OUTPUT_ATTRIBUTE_NAME, SCORE_ACTIVATION, SCORE_OUTPUT_INDEX, TOP_K, +}; +use minifi_native::macros::ComponentIdentifier; +use minifi_native::{ + Content, FlowFileTransform, GetAttribute, GetId, GetProperty, InputStream, Logger, MinifiError, + ProcessError, RouteErrorExt, Schedule, TransformedFlowFile, warn, +}; +use serde::Serialize; +use std::path::Path; +use tract::Tensor; + +mod classify_output_def; + +#[derive(Serialize, Clone, Debug, PartialEq)] +struct Prediction { + class_id: usize, + confidence: f32, + #[serde(skip_serializing_if = "Option::is_none")] + class_name: Option<String>, +} + +fn load_labels(path: &Path) -> Result<Vec<String>, MinifiError> { + let content = std::fs::read_to_string(path).map_err(|e| { + MinifiError::custom(format!("Failed to read labels file '{:?}': {}", path, e)) + })?; + Ok(content + .lines() + .map(|line| line.trim().to_string()) + .collect()) +} + +fn top_k(mut scored: Vec<(usize, f32)>, k: usize) -> Vec<(usize, f32)> { + scored.sort_by(|&(ai, a), &(bi, b)| b.total_cmp(&a).then(ai.cmp(&bi))); + scored.truncate(k); + scored +} + +#[derive(ComponentIdentifier)] +pub(crate) struct ClassifyOutput { + top_k: usize, + score_output_index: usize, + score_activation: ScoreActivation, + confidence_threshold: f32, + labels: Vec<String>, + label_index_offset: usize, +} + +impl Schedule for ClassifyOutput { + fn schedule<Ctx: GetProperty, L: Logger>( + context: &Ctx, + _logger: &L, + ) -> Result<Self, MinifiError> + where + Self: Sized, + { + let top_k = context.get_property(&TOP_K)?; + if top_k == 0 { + return Err(MinifiError::validation("Top K must be >= 1")); + } + let score_output_index = context.get_property(&SCORE_OUTPUT_INDEX)?; + let score_activation = context.get_property(&SCORE_ACTIVATION)?; + let confidence_threshold = context.get_property(&CONFIDENCE_THRESHOLD)?; + + let labels = match context.get_property(&LABELS_FILE_PATH)? { + Some(path) => load_labels(&path)?, + _ => Vec::new(), Review Comment: thats good idea [folded label_index_offset into labels](https://github.com/apache/nifi-minifi-cpp/pull/2258/commits/23d3a4d2d12fc9329ff807362e2f5f1f8858b5e2) -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
