1 /* Copyright 2020 The TensorFlow Authors. 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 #include "tensorflow_lite_support/cc/task/vision/core/classification_head.h"
16 
17 #include "absl/status/status.h"
18 #include "tensorflow_lite_support/cc/common.h"
19 #include "tensorflow_lite_support/cc/port/status_macros.h"
20 #include "tensorflow_lite_support/metadata/metadata_schema_generated.h"
21 
22 namespace tflite {
23 namespace task {
24 namespace vision {
25 
26 using ::absl::StatusCode;
27 using ::tflite::metadata::ModelMetadataExtractor;
28 using ::tflite::support::CreateStatusWithPayload;
29 using ::tflite::support::StatusOr;
30 using ::tflite::support::TfLiteSupportStatus;
31 
BuildClassificationHead(const tflite::metadata::ModelMetadataExtractor & metadata_extractor,const tflite::TensorMetadata & output_tensor_metadata,absl::string_view display_names_locale)32 StatusOr<ClassificationHead> BuildClassificationHead(
33     const tflite::metadata::ModelMetadataExtractor& metadata_extractor,
34     const tflite::TensorMetadata& output_tensor_metadata,
35     absl::string_view display_names_locale) {
36   ClassificationHead head;
37   if (output_tensor_metadata.name() != nullptr) {
38     head.name = output_tensor_metadata.name()->str();
39   }
40 
41   // Build label map, if present.
42   const std::string labels_filename =
43       ModelMetadataExtractor::FindFirstAssociatedFileName(
44           output_tensor_metadata,
45           tflite::AssociatedFileType_TENSOR_AXIS_LABELS);
46   if (!labels_filename.empty()) {
47     ASSIGN_OR_RETURN(absl::string_view labels_file,
48                      metadata_extractor.GetAssociatedFile(labels_filename));
49     const std::string display_names_filename =
50         ModelMetadataExtractor::FindFirstAssociatedFileName(
51             output_tensor_metadata,
52             tflite::AssociatedFileType_TENSOR_AXIS_LABELS,
53             display_names_locale);
54     absl::string_view display_names_file;
55     if (!display_names_filename.empty()) {
56       ASSIGN_OR_RETURN(display_names_file, metadata_extractor.GetAssociatedFile(
57                                                display_names_filename));
58     }
59     ASSIGN_OR_RETURN(head.label_map_items,
60                      BuildLabelMapFromFiles(labels_file, display_names_file));
61   }
62 
63   // Set score threshold, if present.
64   ASSIGN_OR_RETURN(const tflite::ProcessUnit* score_thresholding_process_unit,
65                    ModelMetadataExtractor::FindFirstProcessUnit(
66                        output_tensor_metadata,
67                        tflite::ProcessUnitOptions_ScoreThresholdingOptions));
68   if (score_thresholding_process_unit != nullptr) {
69     head.score_threshold =
70         score_thresholding_process_unit->options_as_ScoreThresholdingOptions()
71             ->global_score_threshold();
72   }
73 
74   // Build score calibration parameters, if present.
75   ASSIGN_OR_RETURN(const tflite::ProcessUnit* score_calibration_process_unit,
76                    ModelMetadataExtractor::FindFirstProcessUnit(
77                        output_tensor_metadata,
78                        tflite::ProcessUnitOptions_ScoreCalibrationOptions));
79   if (score_calibration_process_unit != nullptr) {
80     if (labels_filename.empty()) {
81       return CreateStatusWithPayload(
82           StatusCode::kNotFound,
83           "Using ScoreCalibrationOptions requires a label map to be provided "
84           "as TENSOR_AXIS_LABELS associated file.",
85           TfLiteSupportStatus::kMetadataAssociatedFileNotFoundError);
86     }
87     const std::string score_calibration_filename =
88         ModelMetadataExtractor::FindFirstAssociatedFileName(
89             output_tensor_metadata,
90             tflite::AssociatedFileType_TENSOR_AXIS_SCORE_CALIBRATION);
91     if (score_calibration_filename.empty()) {
92       return CreateStatusWithPayload(
93           StatusCode::kNotFound,
94           "Found ScoreCalibrationOptions but missing required associated "
95           "parameters file with type TENSOR_AXIS_SCORE_CALIBRATION.",
96           TfLiteSupportStatus::kMetadataAssociatedFileNotFoundError);
97     }
98     ASSIGN_OR_RETURN(
99         absl::string_view score_calibration_file,
100         metadata_extractor.GetAssociatedFile(score_calibration_filename));
101     ASSIGN_OR_RETURN(SigmoidCalibrationParameters sigmoid_params,
102                      BuildSigmoidCalibrationParams(
103                          *score_calibration_process_unit
104                               ->options_as_ScoreCalibrationOptions(),
105                          score_calibration_file, head.label_map_items));
106     head.calibration_params = sigmoid_params;
107   }
108 
109   return head;
110 }
111 
112 }  // namespace vision
113 }  // namespace task
114 }  // namespace tflite
115