blob: 24b6fcd2489ad1b04828284c7c2d36e8aae7175d [file] [log] [blame]
alexander3c798932021-03-26 21:42:19 +00001/*
2 * Copyright (c) 2021 Arm Limited. All rights reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17#include "hal.h" /* Brings in platform definitions. */
18#include "Labels.hpp" /* For label strings. */
19#include "UseCaseHandler.hpp" /* Handlers for different user options. */
20#include "Wav2LetterModel.hpp" /* Model class for running inference. */
21#include "UseCaseCommonUtils.hpp" /* Utils functions. */
22#include "AsrClassifier.hpp" /* Classifier. */
23#include "InputFiles.hpp" /* Generated audio clip header. */
24#include "Wav2LetterPreprocess.hpp" /* Pre-processing class. */
25#include "Wav2LetterPostprocess.hpp" /* Post-processing class. */
26
27enum opcodes
28{
29 MENU_OPT_RUN_INF_NEXT = 1, /* Run on next vector. */
30 MENU_OPT_RUN_INF_CHOSEN, /* Run on a user provided vector index. */
31 MENU_OPT_RUN_INF_ALL, /* Run inference on all. */
32 MENU_OPT_SHOW_MODEL_INFO, /* Show model info. */
33 MENU_OPT_LIST_AUDIO_CLIPS /* List the current baked audio clips. */
34};
35
36static void DisplayMenu()
37{
Kshitij Sisodia3c8256d2021-05-24 16:12:40 +010038 printf("\n\n");
39 printf("User input required\n");
alexander3c798932021-03-26 21:42:19 +000040 printf("Enter option number from:\n\n");
41 printf(" %u. Classify next audio clip\n", MENU_OPT_RUN_INF_NEXT);
42 printf(" %u. Classify audio clip at chosen index\n", MENU_OPT_RUN_INF_CHOSEN);
43 printf(" %u. Run classification on all audio clips\n", MENU_OPT_RUN_INF_ALL);
44 printf(" %u. Show NN model info\n", MENU_OPT_SHOW_MODEL_INFO);
45 printf(" %u. List audio clips\n\n", MENU_OPT_LIST_AUDIO_CLIPS);
46 printf(" Choice: ");
47}
48
49/** @brief Verify input and output tensor are of certain min dimensions. */
50static bool VerifyTensorDimensions(const arm::app::Model& model);
51
52/** @brief Gets the number of MFCC features for a single window. */
53static uint32_t GetNumMfccFeatures(const arm::app::Model& model);
54
55/** @brief Gets the number of MFCC feature vectors to be computed. */
56static uint32_t GetNumMfccFeatureVectors(const arm::app::Model& model);
57
58/** @brief Gets the output context length (left and right) for post-processing. */
59static uint32_t GetOutputContextLen(const arm::app::Model& model,
60 uint32_t inputCtxLen);
61
62/** @brief Gets the output inner length for post-processing. */
63static uint32_t GetOutputInnerLen(const arm::app::Model& model,
64 uint32_t outputCtxLen);
65
66void main_loop(hal_platform& platform)
67{
68 arm::app::Wav2LetterModel model; /* Model wrapper object. */
69
70 /* Load the model. */
71 if (!model.Init()) {
72 printf_err("Failed to initialise model\n");
73 return;
74 } else if (!VerifyTensorDimensions(model)) {
75 printf_err("Model's input or output dimension verification failed\n");
76 return;
77 }
78
79 /* Initialise pre-processing. */
80 arm::app::audio::asr::Preprocess prep(
81 GetNumMfccFeatures(model),
82 g_FrameLength,
83 g_FrameStride,
84 GetNumMfccFeatureVectors(model));
85
86 /* Initialise post-processing. */
87 const uint32_t outputCtxLen = GetOutputContextLen(model, g_ctxLen);
88 const uint32_t blankTokenIdx = 28;
89 arm::app::audio::asr::Postprocess postp(
90 outputCtxLen,
91 GetOutputInnerLen(model, outputCtxLen),
92 blankTokenIdx);
93
94 /* Instantiate application context. */
95 arm::app::ApplicationContext caseContext;
96 std::vector <std::string> labels;
97 GetLabelsVector(labels);
98 arm::app::AsrClassifier classifier; /* Classifier wrapper object. */
99
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100100 arm::app::Profiler profiler{&platform, "asr"};
101 caseContext.Set<arm::app::Profiler&>("profiler", profiler);
alexander3c798932021-03-26 21:42:19 +0000102 caseContext.Set<hal_platform&>("platform", platform);
103 caseContext.Set<arm::app::Model&>("model", model);
104 caseContext.Set<uint32_t>("clipIndex", 0);
105 caseContext.Set<uint32_t>("frameLength", g_FrameLength);
106 caseContext.Set<uint32_t>("frameStride", g_FrameStride);
107 caseContext.Set<float>("scoreThreshold", g_ScoreThreshold); /* Score threshold. */
108 caseContext.Set<uint32_t>("ctxLen", g_ctxLen); /* Left and right context length (MFCC feat vectors). */
109 caseContext.Set<const std::vector <std::string>&>("labels", labels);
110 caseContext.Set<arm::app::AsrClassifier&>("classifier", classifier);
111 caseContext.Set<arm::app::audio::asr::Preprocess&>("preprocess", prep);
112 caseContext.Set<arm::app::audio::asr::Postprocess&>("postprocess", postp);
113
114 bool executionSuccessful = true;
115 constexpr bool bUseMenu = NUMBER_OF_FILES > 1 ? true : false;
116
117 /* Loop. */
118 do {
119 int menuOption = MENU_OPT_RUN_INF_NEXT;
120 if (bUseMenu) {
121 DisplayMenu();
122 menuOption = arm::app::ReadUserInputAsInt(platform);
123 printf("\n");
124 }
125 switch (menuOption) {
126 case MENU_OPT_RUN_INF_NEXT:
127 executionSuccessful = ClassifyAudioHandler(
128 caseContext,
129 caseContext.Get<uint32_t>("clipIndex"),
130 false);
131 break;
132 case MENU_OPT_RUN_INF_CHOSEN: {
133 printf(" Enter the audio clip index [0, %d]: ",
134 NUMBER_OF_FILES-1);
135 auto clipIndex = static_cast<uint32_t>(
136 arm::app::ReadUserInputAsInt(platform));
137 executionSuccessful = ClassifyAudioHandler(caseContext,
138 clipIndex,
139 false);
140 break;
141 }
142 case MENU_OPT_RUN_INF_ALL:
143 executionSuccessful = ClassifyAudioHandler(
144 caseContext,
145 caseContext.Get<uint32_t>("clipIndex"),
146 true);
147 break;
148 case MENU_OPT_SHOW_MODEL_INFO:
149 executionSuccessful = model.ShowModelInfoHandler();
150 break;
151 case MENU_OPT_LIST_AUDIO_CLIPS:
152 executionSuccessful = ListFilesHandler(caseContext);
153 break;
154 default:
155 printf("Incorrect choice, try again.");
156 break;
157 }
158 } while (executionSuccessful && bUseMenu);
159 info("Main loop terminated.\n");
160}
161
162static bool VerifyTensorDimensions(const arm::app::Model& model)
163{
164 /* Populate tensor related parameters. */
165 TfLiteTensor* inputTensor = model.GetInputTensor(0);
166 if (!inputTensor->dims) {
167 printf_err("Invalid input tensor dims\n");
168 return false;
169 } else if (inputTensor->dims->size < 3) {
170 printf_err("Input tensor dimension should be >= 3\n");
171 return false;
172 }
173
174 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
175 if (!outputTensor->dims) {
176 printf_err("Invalid output tensor dims\n");
177 return false;
178 } else if (outputTensor->dims->size < 3) {
179 printf_err("Output tensor dimension should be >= 3\n");
180 return false;
181 }
182
183 return true;
184}
185
186static uint32_t GetNumMfccFeatures(const arm::app::Model& model)
187{
188 TfLiteTensor* inputTensor = model.GetInputTensor(0);
189 const int inputCols = inputTensor->dims->data[arm::app::Wav2LetterModel::ms_inputColsIdx];
190 if (0 != inputCols % 3) {
191 printf_err("Number of input columns is not a multiple of 3\n");
192 }
193 return std::max(inputCols/3, 0);
194}
195
196static uint32_t GetNumMfccFeatureVectors(const arm::app::Model& model)
197{
198 TfLiteTensor* inputTensor = model.GetInputTensor(0);
199 const int inputRows = inputTensor->dims->data[arm::app::Wav2LetterModel::ms_inputRowsIdx];
200 return std::max(inputRows, 0);
201}
202
203static uint32_t GetOutputContextLen(const arm::app::Model& model, const uint32_t inputCtxLen)
204{
205 const uint32_t inputRows = GetNumMfccFeatureVectors(model);
206 const uint32_t inputInnerLen = inputRows - (2 * inputCtxLen);
207 constexpr uint32_t ms_outputRowsIdx = arm::app::Wav2LetterModel::ms_outputRowsIdx;
208
209 /* Check to make sure that the input tensor supports the above
210 * context and inner lengths. */
211 if (inputRows <= 2 * inputCtxLen || inputRows <= inputInnerLen) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100212 printf_err("Input rows not compatible with ctx of %" PRIu32 "\n",
alexander3c798932021-03-26 21:42:19 +0000213 inputCtxLen);
214 return 0;
215 }
216
217 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
218 const uint32_t outputRows = std::max(outputTensor->dims->data[ms_outputRowsIdx], 0);
219
220 const float tensorColRatio = static_cast<float>(inputRows)/
221 static_cast<float>(outputRows);
222
223 return std::round(static_cast<float>(inputCtxLen)/tensorColRatio);
224}
225
226static uint32_t GetOutputInnerLen(const arm::app::Model& model,
227 const uint32_t outputCtxLen)
228{
229 constexpr uint32_t ms_outputRowsIdx = arm::app::Wav2LetterModel::ms_outputRowsIdx;
230 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
231 const uint32_t outputRows = std::max(outputTensor->dims->data[ms_outputRowsIdx], 0);
232 return (outputRows - (2 * outputCtxLen));
233}