Copilot commented on code in PR #2258: URL: https://github.com/apache/nifi-minifi-cpp/pull/2258#discussion_r3967441327
########## minifi_rust/extensions/minifi_tensor/src/low_level_processors/filter_bounding_boxes.rs: ########## @@ -0,0 +1,488 @@ +// 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. + +mod filter_bounding_boxes_def; + +use crate::utils::bounding_box::BoundingBox; +use crate::utils::dimensions::Dimensions; +use crate::utils::score_activation::ScoreActivation; +use crate::utils::tensor_helpers::{deserialize_tensors, tensor_as_f32}; +use filter_bounding_boxes_def::SUCCESS; +pub(crate) use filter_bounding_boxes_def::{ + BACKGROUND_CLASS_INDEX, BOX_FORMAT, BOX_OUTPUT_INDEX, CLASS_OUTPUT_INDEX, CONFIDENCE_THRESHOLD, + IOU_THRESHOLD, OUTPUT_ATTRIBUTE_NAME, SCORE_ACTIVATION, SCORE_OUTPUT_INDEX, +}; +use minifi_native::macros::{ComponentIdentifier, PropertyType}; +use minifi_native::{ + Content, FlowFileTransform, GetAttribute, GetId, GetProperty, InputStream, Logger, MinifiError, + ProcessError, RouteErrorExt, Schedule, TransformedFlowFile, debug, +}; +use strum_macros::{Display, EnumString, IntoStaticStr, VariantNames}; +use tract::Tensor; + +#[derive( + Debug, Clone, Copy, PartialEq, Display, EnumString, VariantNames, IntoStaticStr, PropertyType, +)] +#[strum(serialize_all = "PascalCase", const_into_str)] +pub(crate) enum BoxFormat { + /// `[x_min, y_min, x_max, y_max]` — SSD, MobileNet-SSD, most PyTorch models. + Xyxy, + /// `[y_min, x_min, y_max, x_max]` — TensorFlow Object Detection API. + Yxyx, + /// `[cx, cy, w, h]` — YOLOv3/5/8 raw output (center + size). + Cxcywh, +} + +/// Convert the four floats at `box_floats[offset..offset+4]` into a canonical +/// `(x_min, y_min, x_max, y_max)` tuple, regardless of the source layout. +fn decode_box(box_floats: &[f32], offset: usize, format: BoxFormat) -> (f32, f32, f32, f32) { + let a = box_floats[offset]; + let b = box_floats[offset + 1]; + let c = box_floats[offset + 2]; + let d = box_floats[offset + 3]; + match format { + BoxFormat::Xyxy => (a, b, c, d), + BoxFormat::Yxyx => (b, a, d, c), + BoxFormat::Cxcywh => { + let (cx, cy, w, h) = (a, b, c, d); + (cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0) + } + } +} + +/// Result of scoring one box: winning class id + its confidence in [0, 1] for +/// Softmax/Sigmoid, or the raw score for `None`. +struct ScoredClass { + class_id: usize, + confidence: f32, +} + +/// Pick the winning class for one box's per-class scores, applying the chosen +/// activation and honouring the background-class filter. +fn score_box( + logits: &[f32], + activation: ScoreActivation, + background_class_index: Option<usize>, +) -> ScoredClass { + let num_classes = logits.len(); + + let best_valid = logits + .iter() + .enumerate() + .filter(|&(_, &logit)| logit.is_finite()) + .filter(|&(id, _)| match background_class_index { + Some(bg_idx) => !(num_classes > 1 && id == bg_idx), + None => true, + }) + .max_by(|a, b| a.1.total_cmp(b.1)); + + let (class_id, &best_logit) = match best_valid { + Some(val) => val, + None => { + return ScoredClass { + class_id: 0, + confidence: f32::NEG_INFINITY, + }; + } + }; + + let confidence = match activation { + ScoreActivation::Softmax => { + let max_logit = logits + .iter() + .copied() + .filter(|l| l.is_finite()) + .reduce(f32::max) + .unwrap_or(f32::NEG_INFINITY); + let sum_exp: f32 = logits + .iter() + .filter(|l| l.is_finite()) + .map(|&l| (l - max_logit).exp()) + .sum(); + + (best_logit - max_logit).exp() / sum_exp + } + ScoreActivation::Sigmoid => 1.0 / (1.0 + (-best_logit).exp()), + ScoreActivation::None => best_logit, + }; + + ScoredClass { + class_id, + confidence, + } +} + +/// Turn a single per-box score into a confidence for the "separate class-id +/// tensor" path. Sigmoid maps a raw logit to a probability; None passes the +/// score through. Softmax has no meaning over a single scalar (there is no class +/// dimension to normalise over) and is treated as pass-through. +fn activate_scalar(score: f32, activation: ScoreActivation) -> f32 { + match activation { + ScoreActivation::Sigmoid => 1.0 / (1.0 + (-score).exp()), + ScoreActivation::Softmax | ScoreActivation::None => score, + } +} + +#[derive(ComponentIdentifier)] +pub(crate) struct FilterBoundingBoxes { + confidence_threshold: f32, + iou_threshold: f32, + score_output_index: usize, + box_output_index: usize, + box_format: BoxFormat, + score_activation: ScoreActivation, + background_class_index: Option<usize>, + class_output_index: Option<usize>, +} + +impl Schedule for FilterBoundingBoxes { + fn schedule<Ctx: GetProperty, L: Logger>( + context: &Ctx, + _logger: &L, + ) -> Result<Self, MinifiError> { + let confidence_threshold = context.get_property(&CONFIDENCE_THRESHOLD)?; + let iou_threshold = context.get_property(&IOU_THRESHOLD)?; + let score_output_index = context.get_property(&SCORE_OUTPUT_INDEX)?; + let box_output_index = context.get_property(&BOX_OUTPUT_INDEX)?; + let box_format = context.get_property(&BOX_FORMAT)?; + let score_activation = context.get_property(&SCORE_ACTIVATION)?; + let background_class_index = context.get_property(&BACKGROUND_CLASS_INDEX)?; + let class_output_index = context.get_property(&CLASS_OUTPUT_INDEX)?; + + Ok(Self { + confidence_threshold, + iou_threshold, + score_output_index, + box_output_index, + box_format, + score_activation, + background_class_index, + class_output_index, + }) + } +} + +impl FilterBoundingBoxes { + pub(crate) fn filter<'a, Context: GetProperty, LoggerImpl: Logger>( + &self, + context: &Context, + logger: &LoggerImpl, + tensors: Vec<Tensor>, + orig_dim: Dimensions, + target_dim: Dimensions, + ) -> Result<TransformedFlowFile<'a>, ProcessError> { + let score_floats = + tensor_as_f32(&tensors, self.score_output_index).route_err_to_failure()?; + let box_floats = tensor_as_f32(&tensors, self.box_output_index).route_err_to_failure()?; + + let scale = (target_dim.width / orig_dim.width).min(target_dim.height / orig_dim.height); + let pad_x = (target_dim.width - (orig_dim.width * scale)) / 2.0; + let pad_y = (target_dim.height - (orig_dim.height * scale)) / 2.0; + + if !box_floats.len().is_multiple_of(4) { + return Err(MinifiError::custom( + "Box tensor byte length is not a multiple of 16 (4 f32 per box)", + ) + .into()); + } + let num_boxes = box_floats.len() / 4; + if num_boxes == 0 { + debug!(logger, "No boxes to filter; emitting empty array"); + return Ok(TransformedFlowFile::new(&SUCCESS, None) + .with_content(b"[]".to_vec().into()) + .with_attribute("object.count", "0") + .with_attribute("mime.type", "application/json")); + } + + let make_box = |i: usize, class_id: usize, confidence: f32| -> BoundingBox { + let (raw_x_min, raw_y_min, raw_x_max, raw_y_max) = + decode_box(&box_floats, i * 4, self.box_format); + let true_x_min = (((raw_x_min * target_dim.width) - pad_x) / scale) / orig_dim.width; + let true_y_min = (((raw_y_min * target_dim.height) - pad_y) / scale) / orig_dim.height; + let true_x_max = (((raw_x_max * target_dim.width) - pad_x) / scale) / orig_dim.width; + let true_y_max = (((raw_y_max * target_dim.height) - pad_y) / scale) / orig_dim.height; + BoundingBox { + class_id, + confidence, + x_min: true_x_min.clamp(0.0, 1.0), + y_min: true_y_min.clamp(0.0, 1.0), + x_max: true_x_max.clamp(0.0, 1.0), + y_max: true_y_max.clamp(0.0, 1.0), + } + }; + + let mut valid_boxes = Vec::new(); + + match self.class_output_index { + // Separate class-id tensor: one score and one class id per box + Some(class_index) => { + let class_floats = tensor_as_f32(&tensors, class_index).route_err_to_failure()?; + if score_floats.len() != num_boxes || class_floats.len() != num_boxes { + return Err(MinifiError::custom(format!( + "'Class output index' mode expects one score and one class id per box \ + (num_boxes={}, scores={}, classes={})", + num_boxes, + score_floats.len(), + class_floats.len() + )) + .into()); + } + debug!( + logger, + "Filtering {} boxes with separate class-id tensor (activation={:?}, \ + box_format={:?})...", + num_boxes, + self.score_activation, + self.box_format + ); + for i in 0..num_boxes { + let confidence = activate_scalar(score_floats[i], self.score_activation); + if confidence < self.confidence_threshold { + continue; + } + let raw_class = class_floats[i]; + if raw_class < 0.0 { + continue; + } + let class_id = raw_class.round() as usize; + if self.background_class_index == Some(class_id) { + continue; + } + valid_boxes.push(make_box(i, class_id, confidence)); + } Review Comment: In `'Class output index'` mode, `confidence` and `raw_class` are not validated as finite. If `score_floats[i]` is NaN/Inf, `activate_scalar` can yield NaN and the threshold check will not filter it (`NaN < threshold` is false), which can later make JSON serialization fail. Similarly, `raw_class` being NaN will pass `raw_class < 0.0` and then `raw_class.round() as usize` will produce an unintended class id. Filter out non-finite `confidence`/`raw_class` (or treat them as errors) before constructing boxes. ########## minifi_rust/extensions/minifi_tensor/features/environment.py: ########## @@ -0,0 +1,79 @@ +# 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. + +import os +import urllib.request + +from minifi_behave.core.hooks import ( + add_extension_to_minifi_container, + common_after_scenario, + common_before_scenario, +) + +# Model / label / image assets fetched on first use. All hosted on +# public buckets or the sonos/tract repo +REMOTE_ASSETS: dict[str, str] = { + # ImageNet MobileNetV2 classifier (~14 MB) — the reference model used by tract's unit tests + "mobilenetv2-7.onnx": "https://s3.amazonaws.com/tract-ci-builds/tests/mobilenetv2-7.onnx", + # 1000-class ImageNet labels (line N = class N; line 0 is "dummy") + "imagenet_slim_labels.txt": "https://raw.githubusercontent.com/sonos/tract/main/examples/" + "onnx-mobilenet-v2/imagenet_slim_labels.txt", + # Same test image tract's example uses. MobileNetV2 confidently + # classifies this as "military uniform". + "grace_hopper.jpg": "https://raw.githubusercontent.com/sonos/tract/main/examples/" + "onnx-mobilenet-v2/grace_hopper.jpg", Review Comment: The behave test harness downloads executable models and test data from mutable URLs (notably `raw.githubusercontent.com/.../main/...`) without pinning (commit hash) or integrity checks. This is a supply-chain and reproducibility risk for CI. Consider pinning to immutable URLs (commit SHA / release tag) and verifying a known checksum (e.g., SHA-256) after download; also consider adding a download timeout and surfacing a clear error if fetching fails. ########## minifi_rust/extensions/minifi_tensor/src/low_level_processors/filter_bounding_boxes.rs: ########## @@ -0,0 +1,488 @@ +// 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. + +mod filter_bounding_boxes_def; + +use crate::utils::bounding_box::BoundingBox; +use crate::utils::dimensions::Dimensions; +use crate::utils::score_activation::ScoreActivation; +use crate::utils::tensor_helpers::{deserialize_tensors, tensor_as_f32}; +use filter_bounding_boxes_def::SUCCESS; +pub(crate) use filter_bounding_boxes_def::{ + BACKGROUND_CLASS_INDEX, BOX_FORMAT, BOX_OUTPUT_INDEX, CLASS_OUTPUT_INDEX, CONFIDENCE_THRESHOLD, + IOU_THRESHOLD, OUTPUT_ATTRIBUTE_NAME, SCORE_ACTIVATION, SCORE_OUTPUT_INDEX, +}; +use minifi_native::macros::{ComponentIdentifier, PropertyType}; +use minifi_native::{ + Content, FlowFileTransform, GetAttribute, GetId, GetProperty, InputStream, Logger, MinifiError, + ProcessError, RouteErrorExt, Schedule, TransformedFlowFile, debug, +}; +use strum_macros::{Display, EnumString, IntoStaticStr, VariantNames}; +use tract::Tensor; + +#[derive( + Debug, Clone, Copy, PartialEq, Display, EnumString, VariantNames, IntoStaticStr, PropertyType, +)] +#[strum(serialize_all = "PascalCase", const_into_str)] +pub(crate) enum BoxFormat { + /// `[x_min, y_min, x_max, y_max]` — SSD, MobileNet-SSD, most PyTorch models. + Xyxy, + /// `[y_min, x_min, y_max, x_max]` — TensorFlow Object Detection API. + Yxyx, + /// `[cx, cy, w, h]` — YOLOv3/5/8 raw output (center + size). + Cxcywh, +} + +/// Convert the four floats at `box_floats[offset..offset+4]` into a canonical +/// `(x_min, y_min, x_max, y_max)` tuple, regardless of the source layout. +fn decode_box(box_floats: &[f32], offset: usize, format: BoxFormat) -> (f32, f32, f32, f32) { + let a = box_floats[offset]; + let b = box_floats[offset + 1]; + let c = box_floats[offset + 2]; + let d = box_floats[offset + 3]; + match format { + BoxFormat::Xyxy => (a, b, c, d), + BoxFormat::Yxyx => (b, a, d, c), + BoxFormat::Cxcywh => { + let (cx, cy, w, h) = (a, b, c, d); + (cx - w / 2.0, cy - h / 2.0, cx + w / 2.0, cy + h / 2.0) + } + } +} + +/// Result of scoring one box: winning class id + its confidence in [0, 1] for +/// Softmax/Sigmoid, or the raw score for `None`. +struct ScoredClass { + class_id: usize, + confidence: f32, +} + +/// Pick the winning class for one box's per-class scores, applying the chosen +/// activation and honouring the background-class filter. +fn score_box( + logits: &[f32], + activation: ScoreActivation, + background_class_index: Option<usize>, +) -> ScoredClass { + let num_classes = logits.len(); + + let best_valid = logits + .iter() + .enumerate() + .filter(|&(_, &logit)| logit.is_finite()) + .filter(|&(id, _)| match background_class_index { + Some(bg_idx) => !(num_classes > 1 && id == bg_idx), + None => true, + }) + .max_by(|a, b| a.1.total_cmp(b.1)); + + let (class_id, &best_logit) = match best_valid { + Some(val) => val, + None => { + return ScoredClass { + class_id: 0, + confidence: f32::NEG_INFINITY, + }; + } + }; + + let confidence = match activation { + ScoreActivation::Softmax => { + let max_logit = logits + .iter() + .copied() + .filter(|l| l.is_finite()) + .reduce(f32::max) + .unwrap_or(f32::NEG_INFINITY); + let sum_exp: f32 = logits + .iter() + .filter(|l| l.is_finite()) + .map(|&l| (l - max_logit).exp()) + .sum(); + + (best_logit - max_logit).exp() / sum_exp + } + ScoreActivation::Sigmoid => 1.0 / (1.0 + (-best_logit).exp()), + ScoreActivation::None => best_logit, + }; + + ScoredClass { + class_id, + confidence, + } +} + +/// Turn a single per-box score into a confidence for the "separate class-id +/// tensor" path. Sigmoid maps a raw logit to a probability; None passes the +/// score through. Softmax has no meaning over a single scalar (there is no class +/// dimension to normalise over) and is treated as pass-through. +fn activate_scalar(score: f32, activation: ScoreActivation) -> f32 { + match activation { + ScoreActivation::Sigmoid => 1.0 / (1.0 + (-score).exp()), + ScoreActivation::Softmax | ScoreActivation::None => score, + } +} + +#[derive(ComponentIdentifier)] +pub(crate) struct FilterBoundingBoxes { + confidence_threshold: f32, + iou_threshold: f32, + score_output_index: usize, + box_output_index: usize, + box_format: BoxFormat, + score_activation: ScoreActivation, + background_class_index: Option<usize>, + class_output_index: Option<usize>, +} + +impl Schedule for FilterBoundingBoxes { + fn schedule<Ctx: GetProperty, L: Logger>( + context: &Ctx, + _logger: &L, + ) -> Result<Self, MinifiError> { + let confidence_threshold = context.get_property(&CONFIDENCE_THRESHOLD)?; + let iou_threshold = context.get_property(&IOU_THRESHOLD)?; + let score_output_index = context.get_property(&SCORE_OUTPUT_INDEX)?; + let box_output_index = context.get_property(&BOX_OUTPUT_INDEX)?; + let box_format = context.get_property(&BOX_FORMAT)?; + let score_activation = context.get_property(&SCORE_ACTIVATION)?; + let background_class_index = context.get_property(&BACKGROUND_CLASS_INDEX)?; + let class_output_index = context.get_property(&CLASS_OUTPUT_INDEX)?; + + Ok(Self { + confidence_threshold, + iou_threshold, + score_output_index, + box_output_index, + box_format, + score_activation, + background_class_index, + class_output_index, + }) + } +} + +impl FilterBoundingBoxes { + pub(crate) fn filter<'a, Context: GetProperty, LoggerImpl: Logger>( + &self, + context: &Context, + logger: &LoggerImpl, + tensors: Vec<Tensor>, + orig_dim: Dimensions, + target_dim: Dimensions, + ) -> Result<TransformedFlowFile<'a>, ProcessError> { + let score_floats = + tensor_as_f32(&tensors, self.score_output_index).route_err_to_failure()?; + let box_floats = tensor_as_f32(&tensors, self.box_output_index).route_err_to_failure()?; + + let scale = (target_dim.width / orig_dim.width).min(target_dim.height / orig_dim.height); + let pad_x = (target_dim.width - (orig_dim.width * scale)) / 2.0; + let pad_y = (target_dim.height - (orig_dim.height * scale)) / 2.0; + + if !box_floats.len().is_multiple_of(4) { + return Err(MinifiError::custom( + "Box tensor byte length is not a multiple of 16 (4 f32 per box)", + ) + .into()); + } + let num_boxes = box_floats.len() / 4; + if num_boxes == 0 { + debug!(logger, "No boxes to filter; emitting empty array"); + return Ok(TransformedFlowFile::new(&SUCCESS, None) + .with_content(b"[]".to_vec().into()) + .with_attribute("object.count", "0") + .with_attribute("mime.type", "application/json")); + } + + let make_box = |i: usize, class_id: usize, confidence: f32| -> BoundingBox { + let (raw_x_min, raw_y_min, raw_x_max, raw_y_max) = + decode_box(&box_floats, i * 4, self.box_format); + let true_x_min = (((raw_x_min * target_dim.width) - pad_x) / scale) / orig_dim.width; + let true_y_min = (((raw_y_min * target_dim.height) - pad_y) / scale) / orig_dim.height; + let true_x_max = (((raw_x_max * target_dim.width) - pad_x) / scale) / orig_dim.width; + let true_y_max = (((raw_y_max * target_dim.height) - pad_y) / scale) / orig_dim.height; + BoundingBox { + class_id, + confidence, + x_min: true_x_min.clamp(0.0, 1.0), + y_min: true_y_min.clamp(0.0, 1.0), + x_max: true_x_max.clamp(0.0, 1.0), + y_max: true_y_max.clamp(0.0, 1.0), + } + }; + + let mut valid_boxes = Vec::new(); + + match self.class_output_index { + // Separate class-id tensor: one score and one class id per box + Some(class_index) => { + let class_floats = tensor_as_f32(&tensors, class_index).route_err_to_failure()?; + if score_floats.len() != num_boxes || class_floats.len() != num_boxes { + return Err(MinifiError::custom(format!( + "'Class output index' mode expects one score and one class id per box \ + (num_boxes={}, scores={}, classes={})", + num_boxes, + score_floats.len(), + class_floats.len() + )) + .into()); + } + debug!( + logger, + "Filtering {} boxes with separate class-id tensor (activation={:?}, \ + box_format={:?})...", + num_boxes, + self.score_activation, + self.box_format + ); + for i in 0..num_boxes { + let confidence = activate_scalar(score_floats[i], self.score_activation); + if confidence < self.confidence_threshold { + continue; + } + let raw_class = class_floats[i]; + if raw_class < 0.0 { + continue; + } + let class_id = raw_class.round() as usize; + if self.background_class_index == Some(class_id) { + continue; + } + valid_boxes.push(make_box(i, class_id, confidence)); + } + } + // Per-class score matrix: argmax over classes per box. + None => { + if !score_floats.len().is_multiple_of(num_boxes) { + return Err(MinifiError::custom(format!( + "Scores length ({}) not divisible by number of boxes ({})", + score_floats.len(), + num_boxes + )) + .into()); + } + let num_classes = score_floats.len() / num_boxes; + debug!( + logger, + "Filtering {} boxes across {} potential classes (activation={:?}, \ + box_format={:?})...", + num_boxes, + num_classes, + self.score_activation, + self.box_format + ); + for i in 0..num_boxes { + let logits = &score_floats[i * num_classes..(i + 1) * num_classes]; + let scored = + score_box(logits, self.score_activation, self.background_class_index); + if scored.confidence >= self.confidence_threshold { + valid_boxes.push(make_box(i, scored.class_id, scored.confidence)); + } + } + } + } + + debug!( + logger, + "Found {} boxes exceeding the {} threshold.", + valid_boxes.len(), + self.confidence_threshold + ); + + let filtered_boxes = + BoundingBox::apply_non_maximum_suppression(valid_boxes, self.iou_threshold); + + let json_output = serde_json::to_vec(&filtered_boxes).route_err_to_failure()?; + + let (content, extra_attribute) = match context.get_property(&OUTPUT_ATTRIBUTE_NAME)? { + None => (Some(Content::Buffer(json_output)), None), + Some(output_attr) => ( + None, + Some((output_attr, serde_json::to_string(&filtered_boxes).unwrap())), Review Comment: `serde_json::to_string(&filtered_boxes).unwrap()` can panic (e.g., if a NaN sneaks into `confidence` or coordinates). Since this is in the flow path, it should not panic—convert the serialization error into a routed failure (consistent with `to_vec(...).route_err_to_failure()?`). ########## minifi_rust/extensions/minifi_tensor/src/services/tract_model_service.rs: ########## @@ -0,0 +1,179 @@ +// 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::services::tract_model_service::service_definition::{MODEL_FILE_PATH, MODEL_FORMAT}; +use minifi_native::macros::{ComponentIdentifier, PropertyType}; +use minifi_native::{EnableControllerService, GetProperty, Logger, MinifiError, trace}; +use std::path::Path; +use strum_macros::{Display, EnumString, IntoStaticStr, VariantNames}; +use tract::__ndarray_interop::anyhow; +use tract::prelude::*; Review Comment: `run_inference` exposes an `anyhow::Result` sourced from `tract::__ndarray_interop::anyhow` (an internal-looking module path) while most call sites in this PR route errors via `MinifiError`/`ProcessError`. Prefer a stable, crate-owned error boundary here (e.g., `Result<Vec<Tensor>, MinifiError>` with explicit conversion) or a stable Tract result type, so downstream processors can route failures without relying on an internal Tract module path. ########## minifi_rust/extensions/minifi_tensor/src/services/tract_model_service.rs: ########## @@ -0,0 +1,179 @@ +// 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::services::tract_model_service::service_definition::{MODEL_FILE_PATH, MODEL_FORMAT}; +use minifi_native::macros::{ComponentIdentifier, PropertyType}; +use minifi_native::{EnableControllerService, GetProperty, Logger, MinifiError, trace}; +use std::path::Path; +use strum_macros::{Display, EnumString, IntoStaticStr, VariantNames}; +use tract::__ndarray_interop::anyhow; +use tract::prelude::*; + +mod service_definition; + +#[derive( + Debug, Clone, Copy, PartialEq, Display, EnumString, VariantNames, IntoStaticStr, PropertyType, +)] +#[strum(serialize_all = "PascalCase", const_into_str)] +pub(crate) enum ModelFormat { + Auto, + Onnx, + Nnef, +} + +/// Resolved format after any auto-detection. +#[derive(Debug, Clone, Copy, PartialEq)] +enum ResolvedFormat { + Onnx, + Nnef, +} + +impl ModelFormat { + fn resolve(self, path: &Path) -> Result<ResolvedFormat, MinifiError> { + match self { + ModelFormat::Onnx => Ok(ResolvedFormat::Onnx), + ModelFormat::Nnef => Ok(ResolvedFormat::Nnef), + ModelFormat::Auto => { + let path_str = path.to_string_lossy().to_ascii_lowercase(); + if path_str.ends_with(".onnx") { + Ok(ResolvedFormat::Onnx) + } else if path_str.ends_with(".nnef") + || path_str.ends_with(".nnef.tgz") + || path_str.ends_with(".nnef.tar") + || path_str.ends_with(".nnef.tar.gz") + || path.is_dir() + { + Ok(ResolvedFormat::Nnef) + } else { + Err(MinifiError::custom(format!( + "Could not auto-detect model format from '{:?}'. Set 'Model format' to \ + 'Onnx' or 'Nnef' explicitly.", + path + ))) + } + } + } + } +} + +#[derive(ComponentIdentifier)] +pub(crate) struct TractModelService { + runnable_model: Runnable, +} + +impl EnableControllerService for TractModelService { + fn enable<Ctx: GetProperty, L: Logger>(context: &Ctx, logger: &L) -> Result<Self, MinifiError> + where + Self: Sized, + { + let model_path = context.get_property(&MODEL_FILE_PATH)?; + let format = context.get_property(&MODEL_FORMAT)?; + let resolved = format.resolve(&model_path)?; + + trace!( + logger, + "Loading Tract model ({:?}) from: {:?}", resolved, model_path + ); + + let model = match resolved { + ResolvedFormat::Onnx => onnx()?.load(&model_path)?.into_model()?, + ResolvedFormat::Nnef => nnef()?.load(&model_path)?, + }; + + let runtime = runtime_for_name("default")?; + let runnable_model = runtime.prepare(model)?; + + trace!(logger, "Successfully loaded and compiled Tract model."); + + Ok(Self { runnable_model }) + } +} + +impl TractModelService { + pub fn run_inference( + &self, + inputs: impl IntoIterator<Item = Tensor>, + ) -> anyhow::Result<Vec<Tensor>> { + let vec_inputs: Vec<Tensor> = inputs.into_iter().collect(); + + self.runnable_model.run(vec_inputs) + } +} Review Comment: `run_inference` exposes an `anyhow::Result` sourced from `tract::__ndarray_interop::anyhow` (an internal-looking module path) while most call sites in this PR route errors via `MinifiError`/`ProcessError`. Prefer a stable, crate-owned error boundary here (e.g., `Result<Vec<Tensor>, MinifiError>` with explicit conversion) or a stable Tract result type, so downstream processors can route failures without relying on an internal Tract module path. ########## minifi_rust/extensions/minifi_tensor/features/environment.py: ########## @@ -0,0 +1,79 @@ +# 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. + +import os +import urllib.request + +from minifi_behave.core.hooks import ( + add_extension_to_minifi_container, + common_after_scenario, + common_before_scenario, +) + +# Model / label / image assets fetched on first use. All hosted on +# public buckets or the sonos/tract repo +REMOTE_ASSETS: dict[str, str] = { + # ImageNet MobileNetV2 classifier (~14 MB) — the reference model used by tract's unit tests + "mobilenetv2-7.onnx": "https://s3.amazonaws.com/tract-ci-builds/tests/mobilenetv2-7.onnx", + # 1000-class ImageNet labels (line N = class N; line 0 is "dummy") + "imagenet_slim_labels.txt": "https://raw.githubusercontent.com/sonos/tract/main/examples/" + "onnx-mobilenet-v2/imagenet_slim_labels.txt", + # Same test image tract's example uses. MobileNetV2 confidently + # classifies this as "military uniform". + "grace_hopper.jpg": "https://raw.githubusercontent.com/sonos/tract/main/examples/" + "onnx-mobilenet-v2/grace_hopper.jpg", + # UltraFace RFB-320 (~1.2 MB): 2-output SSD-style detector matching the + # existing FilterBoundingBoxes defaults (Xyxy boxes, class 0 = background, + # softmax over 2 classes: background/face). 320x240 RGB, mean=127, std=128. + "version-RFB-320.onnx": "https://github.com/onnx/models/raw/refs/heads/main/validated/vision/" + "body_analysis/ultraface/models/version-RFB-320.onnx", +} + + +def _ensure_asset(cache_dir: str, filename: str) -> str: + dest = os.path.join(cache_dir, filename) + if os.path.exists(dest): + return dest + url = REMOTE_ASSETS[filename] + os.makedirs(cache_dir, exist_ok=True) + tmp = dest + ".part" + print(f"[minifi_tensor tests] fetching {filename} from {url}") + urllib.request.urlretrieve(url, tmp) + os.replace(tmp, dest) Review Comment: The behave test harness downloads executable models and test data from mutable URLs (notably `raw.githubusercontent.com/.../main/...`) without pinning (commit hash) or integrity checks. This is a supply-chain and reproducibility risk for CI. Consider pinning to immutable URLs (commit SHA / release tag) and verifying a known checksum (e.g., SHA-256) after download; also consider adding a download timeout and surfacing a clear error if fetching fails. ########## minifi_rust/extensions/minifi_tensor/src/low_level_processors/image_to_tensor.rs: ########## @@ -0,0 +1,610 @@ +// 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. +pub(crate) mod image_to_tensor_def; + +use crate::utils::dimensions::Dimensions; +use crate::utils::per_channel_f32::PerChannelF32; +use crate::utils::tensor_helpers::{MinifiDatumType, load_as_image}; +pub(crate) use image_to_tensor_def::{ + COLOR_FORMAT, LETTERBOX_PAD_VALUE, MEAN, PIXEL_DIVISOR, RESIZE_FILTER, RESIZE_MODE, STD_DEV, + TARGET_HEIGHT, TARGET_WIDTH, TENSOR_SHAPE_FORMAT, +}; +use image_to_tensor_def::{ + IMG_ORG_HEIGHT_ATTR, IMG_ORG_WIDTH_ATTR, SUCCESS, TENSOR_DTYPE_ATTR, TENSOR_SHAPE_ATTR, +}; +use image_to_tensor_def::{IMG_TRG_HEIGHT_ATTR, IMG_TRG_WIDTH_ATTR, TENSORS_LEN_ATTR}; +use minifi_native::macros::{ComponentIdentifier, PropertyType}; +use minifi_native::{ + FlowFileTransform, GetAttribute, GetControllerService, GetId, GetProperty, InputStream, Logger, + MinifiError, ProcessError, RouteErrorExt, Schedule, TransformedFlowFile, +}; +use strum_macros::{Display, EnumString, IntoStaticStr, VariantNames}; +use tract::Tensor; + +tract::impl_ndarray_interop!(); + +#[derive( + Debug, Clone, Copy, PartialEq, Display, EnumString, VariantNames, IntoStaticStr, PropertyType, +)] +#[strum(serialize_all = "PascalCase", const_into_str)] +pub(crate) enum ResizeFilter { + Nearest, + Bilinear, + Bicubic, + Lanczos3, +} + +impl From<ResizeFilter> for image::imageops::FilterType { + fn from(filter: ResizeFilter) -> Self { + match filter { + ResizeFilter::Nearest => image::imageops::FilterType::Nearest, + ResizeFilter::Bilinear => image::imageops::FilterType::Triangle, + ResizeFilter::Bicubic => image::imageops::FilterType::CatmullRom, + ResizeFilter::Lanczos3 => image::imageops::FilterType::Lanczos3, + } + } +} + +#[derive( + Debug, Clone, Copy, PartialEq, Display, EnumString, VariantNames, IntoStaticStr, PropertyType, +)] +#[strum(serialize_all = "UPPERCASE", const_into_str)] +pub(crate) enum ColorFormat { + Rgb, + Bgr, + Grayscale, +} + +#[derive( + Debug, Clone, Copy, PartialEq, Display, EnumString, VariantNames, IntoStaticStr, PropertyType, +)] +#[strum(serialize_all = "UPPERCASE", const_into_str)] +pub(crate) enum TensorShapeFormat { + Chw, // center, height, width + Hwc, // height, width, center Review Comment: The comments for `TensorShapeFormat` use `center` where `channel` is intended. This is misleading for users/developers working with CHW/HWC layouts. -- 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]
