blob: 3a6931560833542c14b31130c818feb068e0ea7f [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 "InputFiles.hpp" /* For input images. */
19#include "Labels_dscnn.hpp" /* For DS-CNN label strings. */
20#include "Labels_wav2letter.hpp" /* For Wav2Letter label strings. */
21#include "Classifier.hpp" /* KWS classifier. */
22#include "AsrClassifier.hpp" /* ASR classifier. */
23#include "DsCnnModel.hpp" /* KWS model class for running inference. */
24#include "Wav2LetterModel.hpp" /* ASR model class for running inference. */
25#include "UseCaseCommonUtils.hpp" /* Utils functions. */
26#include "UseCaseHandler.hpp" /* Handlers for different user options. */
27#include "Wav2LetterPreprocess.hpp" /* ASR pre-processing class. */
28#include "Wav2LetterPostprocess.hpp"/* ASR post-processing class. */
29
30using KwsClassifier = arm::app::Classifier;
31
32enum opcodes
33{
34 MENU_OPT_RUN_INF_NEXT = 1, /* Run on next vector. */
35 MENU_OPT_RUN_INF_CHOSEN, /* Run on a user provided vector index. */
36 MENU_OPT_RUN_INF_ALL, /* Run inference on all. */
37 MENU_OPT_SHOW_MODEL_INFO, /* Show model info. */
38 MENU_OPT_LIST_AUDIO_CLIPS /* List the current baked audio clips. */
39};
40
41static void DisplayMenu()
42{
Kshitij Sisodia3c8256d2021-05-24 16:12:40 +010043 printf("\n\n");
44 printf("User input required\n");
alexander3c798932021-03-26 21:42:19 +000045 printf("Enter option number from:\n\n");
46 printf(" %u. Classify next audio clip\n", MENU_OPT_RUN_INF_NEXT);
47 printf(" %u. Classify audio clip at chosen index\n", MENU_OPT_RUN_INF_CHOSEN);
48 printf(" %u. Run classification on all audio clips\n", MENU_OPT_RUN_INF_ALL);
49 printf(" %u. Show NN model info\n", MENU_OPT_SHOW_MODEL_INFO);
50 printf(" %u. List audio clips\n\n", MENU_OPT_LIST_AUDIO_CLIPS);
51 printf(" Choice: ");
52}
53
54/** @brief Gets the number of MFCC features for a single window. */
55static uint32_t GetNumMfccFeatures(const arm::app::Model& model);
56
57/** @brief Gets the number of MFCC feature vectors to be computed. */
58static uint32_t GetNumMfccFeatureVectors(const arm::app::Model& model);
59
60/** @brief Gets the output context length (left and right) for post-processing. */
61static uint32_t GetOutputContextLen(const arm::app::Model& model,
62 uint32_t inputCtxLen);
63
64/** @brief Gets the output inner length for post-processing. */
65static uint32_t GetOutputInnerLen(const arm::app::Model& model,
66 uint32_t outputCtxLen);
67
68void main_loop(hal_platform& platform)
69{
70 /* Model wrapper objects. */
71 arm::app::DsCnnModel kwsModel;
72 arm::app::Wav2LetterModel asrModel;
73
74 /* Load the models. */
75 if (!kwsModel.Init()) {
76 printf_err("Failed to initialise KWS model\n");
77 return;
78 }
79
80 /* Initialise the asr model using the same allocator from KWS
81 * to re-use the tensor arena. */
82 if (!asrModel.Init(kwsModel.GetAllocator())) {
83 printf_err("Failed to initalise ASR model\n");
84 return;
85 }
86
87 /* Initialise ASR pre-processing. */
88 arm::app::audio::asr::Preprocess prep(
89 GetNumMfccFeatures(asrModel),
90 arm::app::asr::g_FrameLength,
91 arm::app::asr::g_FrameStride,
92 GetNumMfccFeatureVectors(asrModel));
93
94 /* Initialise ASR post-processing. */
95 const uint32_t outputCtxLen = GetOutputContextLen(asrModel, arm::app::asr::g_ctxLen);
96 const uint32_t blankTokenIdx = 28;
97 arm::app::audio::asr::Postprocess postp(
98 outputCtxLen,
99 GetOutputInnerLen(asrModel, outputCtxLen),
100 blankTokenIdx);
101
102 /* Instantiate application context. */
103 arm::app::ApplicationContext caseContext;
104
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100105 arm::app::Profiler profiler{&platform, "kws_asr"};
106 caseContext.Set<arm::app::Profiler&>("profiler", profiler);
107
alexander3c798932021-03-26 21:42:19 +0000108 caseContext.Set<hal_platform&>("platform", platform);
109 caseContext.Set<arm::app::Model&>("kwsmodel", kwsModel);
110 caseContext.Set<arm::app::Model&>("asrmodel", asrModel);
111 caseContext.Set<uint32_t>("clipIndex", 0);
112 caseContext.Set<uint32_t>("ctxLen", arm::app::asr::g_ctxLen); /* Left and right context length (MFCC feat vectors). */
113 caseContext.Set<int>("kwsframeLength", arm::app::kws::g_FrameLength);
114 caseContext.Set<int>("kwsframeStride", arm::app::kws::g_FrameStride);
115 caseContext.Set<float>("kwsscoreThreshold", arm::app::kws::g_ScoreThreshold); /* Normalised score threshold. */
116 caseContext.Set<uint32_t >("kwsNumMfcc", arm::app::kws::g_NumMfcc);
117 caseContext.Set<uint32_t >("kwsNumAudioWins", arm::app::kws::g_NumAudioWins);
118
119 caseContext.Set<int>("asrframeLength", arm::app::asr::g_FrameLength);
120 caseContext.Set<int>("asrframeStride", arm::app::asr::g_FrameStride);
121 caseContext.Set<float>("asrscoreThreshold", arm::app::asr::g_ScoreThreshold); /* Normalised score threshold. */
122
123 KwsClassifier kwsClassifier; /* Classifier wrapper object. */
124 arm::app::AsrClassifier asrClassifier; /* Classifier wrapper object. */
125 caseContext.Set<arm::app::Classifier&>("kwsclassifier", kwsClassifier);
126 caseContext.Set<arm::app::AsrClassifier&>("asrclassifier", asrClassifier);
127
128 caseContext.Set<arm::app::audio::asr::Preprocess&>("preprocess", prep);
129 caseContext.Set<arm::app::audio::asr::Postprocess&>("postprocess", postp);
130
131 std::vector<std::string> asrLabels;
132 arm::app::asr::GetLabelsVector(asrLabels);
133 std::vector<std::string> kwsLabels;
134 arm::app::kws::GetLabelsVector(kwsLabels);
135 caseContext.Set<const std::vector <std::string>&>("asrlabels", asrLabels);
136 caseContext.Set<const std::vector <std::string>&>("kwslabels", kwsLabels);
137
138 /* Index of the kws outputs we trigger ASR on. */
139 caseContext.Set<uint32_t>("keywordindex", 2);
140
141 /* Loop. */
142 bool executionSuccessful = true;
143 constexpr bool bUseMenu = NUMBER_OF_FILES > 1 ? true : false;
144
145 /* Loop. */
146 do {
147 int menuOption = MENU_OPT_RUN_INF_NEXT;
148 if (bUseMenu) {
149 DisplayMenu();
150 menuOption = arm::app::ReadUserInputAsInt(platform);
151 printf("\n");
152 }
153 switch (menuOption) {
154 case MENU_OPT_RUN_INF_NEXT:
155 executionSuccessful = ClassifyAudioHandler(
156 caseContext,
157 caseContext.Get<uint32_t>("clipIndex"),
158 false);
159 break;
160 case MENU_OPT_RUN_INF_CHOSEN: {
161 printf(" Enter the audio clip index [0, %d]: ",
162 NUMBER_OF_FILES-1);
163 auto clipIndex = static_cast<uint32_t>(
164 arm::app::ReadUserInputAsInt(platform));
165 executionSuccessful = ClassifyAudioHandler(caseContext,
166 clipIndex,
167 false);
168 break;
169 }
170 case MENU_OPT_RUN_INF_ALL:
171 executionSuccessful = ClassifyAudioHandler(
172 caseContext,
173 caseContext.Get<uint32_t>("clipIndex"),
174 true);
175 break;
176 case MENU_OPT_SHOW_MODEL_INFO:
177 executionSuccessful = kwsModel.ShowModelInfoHandler();
178 executionSuccessful = asrModel.ShowModelInfoHandler();
179 break;
180 case MENU_OPT_LIST_AUDIO_CLIPS:
181 executionSuccessful = ListFilesHandler(caseContext);
182 break;
183 default:
184 printf("Incorrect choice, try again.");
185 break;
186 }
187 } while (executionSuccessful && bUseMenu);
188 info("Main loop terminated.\n");
189}
190
191static uint32_t GetNumMfccFeatures(const arm::app::Model& model)
192{
193 TfLiteTensor* inputTensor = model.GetInputTensor(0);
194 const int inputCols = inputTensor->dims->data[arm::app::Wav2LetterModel::ms_inputColsIdx];
195 if (0 != inputCols % 3) {
196 printf_err("Number of input columns is not a multiple of 3\n");
197 }
198 return std::max(inputCols/3, 0);
199}
200
201static uint32_t GetNumMfccFeatureVectors(const arm::app::Model& model)
202{
203 TfLiteTensor* inputTensor = model.GetInputTensor(0);
204 const int inputRows = inputTensor->dims->data[arm::app::Wav2LetterModel::ms_inputRowsIdx];
205 return std::max(inputRows, 0);
206}
207
208static uint32_t GetOutputContextLen(const arm::app::Model& model, const uint32_t inputCtxLen)
209{
210 const uint32_t inputRows = GetNumMfccFeatureVectors(model);
211 const uint32_t inputInnerLen = inputRows - (2 * inputCtxLen);
212 constexpr uint32_t ms_outputRowsIdx = arm::app::Wav2LetterModel::ms_outputRowsIdx;
213
214 /* Check to make sure that the input tensor supports the above context and inner lengths. */
215 if (inputRows <= 2 * inputCtxLen || inputRows <= inputInnerLen) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100216 printf_err("Input rows not compatible with ctx of %" PRIu32 "\n",
alexander3c798932021-03-26 21:42:19 +0000217 inputCtxLen);
218 return 0;
219 }
220
221 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
222 const uint32_t outputRows = std::max(outputTensor->dims->data[ms_outputRowsIdx], 0);
223
224 const float tensorColRatio = static_cast<float>(inputRows)/
225 static_cast<float>(outputRows);
226
227 return std::round(static_cast<float>(inputCtxLen)/tensorColRatio);
228}
229
230static uint32_t GetOutputInnerLen(const arm::app::Model& model,
231 const uint32_t outputCtxLen)
232{
233 constexpr uint32_t ms_outputRowsIdx = arm::app::Wav2LetterModel::ms_outputRowsIdx;
234 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
235 const uint32_t outputRows = std::max(outputTensor->dims->data[ms_outputRowsIdx], 0);
236 return (outputRows - (2 * outputCtxLen));
237}