blob: d46925538bbeafd222360d26f098184d4b449ab8 [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 "UseCaseHandler.hpp"
18
19#include "InputFiles.hpp"
20#include "AsrClassifier.hpp"
21#include "Wav2LetterModel.hpp"
22#include "hal.h"
23#include "Wav2LetterMfcc.hpp"
24#include "AudioUtils.hpp"
25#include "UseCaseCommonUtils.hpp"
26#include "AsrResult.hpp"
27#include "Wav2LetterPreprocess.hpp"
28#include "Wav2LetterPostprocess.hpp"
29#include "OutputDecode.hpp"
30
31namespace arm {
32namespace app {
33
34 /**
alexander3c798932021-03-26 21:42:19 +000035 * @brief Presents inference results using the data presentation
36 * object.
37 * @param[in] platform Reference to the hal platform object.
38 * @param[in] results Vector of classification results to be displayed.
alexander3c798932021-03-26 21:42:19 +000039 * @return true if successful, false otherwise.
40 **/
alexanderc350cdc2021-04-29 20:36:09 +010041 static bool PresentInferenceResult(
alexander3c798932021-03-26 21:42:19 +000042 hal_platform& platform,
43 const std::vector<arm::app::asr::AsrResult>& results);
44
45 /* Audio inference classification handler. */
46 bool ClassifyAudioHandler(ApplicationContext& ctx, uint32_t clipIndex, bool runAll)
47 {
48 constexpr uint32_t dataPsnTxtInfStartX = 20;
49 constexpr uint32_t dataPsnTxtInfStartY = 40;
50
51 auto& platform = ctx.Get<hal_platform&>("platform");
52 platform.data_psn->clear(COLOR_BLACK);
53
Isabella Gottardi8df12f32021-04-07 17:15:31 +010054 auto& profiler = ctx.Get<Profiler&>("profiler");
55
alexander3c798932021-03-26 21:42:19 +000056 /* If the request has a valid size, set the audio index. */
57 if (clipIndex < NUMBER_OF_FILES) {
Éanna Ó Catháin8f958872021-09-15 09:32:30 +010058 if (!SetAppCtxIfmIdx(ctx, clipIndex,"clipIndex")) {
alexander3c798932021-03-26 21:42:19 +000059 return false;
60 }
61 }
62
63 /* Get model reference. */
64 auto& model = ctx.Get<Model&>("model");
65 if (!model.IsInited()) {
66 printf_err("Model is not initialised! Terminating processing.\n");
67 return false;
68 }
69
70 /* Get score threshold to be applied for the classifier (post-inference). */
71 auto scoreThreshold = ctx.Get<float>("scoreThreshold");
72
73 /* Get tensors. Dimensions of the tensor should have been verified by
74 * the callee. */
75 TfLiteTensor* inputTensor = model.GetInputTensor(0);
76 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
77 const uint32_t inputRows = inputTensor->dims->data[arm::app::Wav2LetterModel::ms_inputRowsIdx];
78
79 /* Populate MFCC related parameters. */
80 auto mfccParamsWinLen = ctx.Get<uint32_t>("frameLength");
81 auto mfccParamsWinStride = ctx.Get<uint32_t>("frameStride");
82
83 /* Populate ASR inference context and inner lengths for input. */
84 auto inputCtxLen = ctx.Get<uint32_t>("ctxLen");
85 const uint32_t inputInnerLen = inputRows - (2 * inputCtxLen);
86
87 /* Audio data stride corresponds to inputInnerLen feature vectors. */
88 const uint32_t audioParamsWinLen = (inputRows - 1) * mfccParamsWinStride + (mfccParamsWinLen);
89 const uint32_t audioParamsWinStride = inputInnerLen * mfccParamsWinStride;
90 const float audioParamsSecondsPerSample = (1.0/audio::Wav2LetterMFCC::ms_defaultSamplingFreq);
91
92 /* Get pre/post-processing objects. */
93 auto& prep = ctx.Get<audio::asr::Preprocess&>("preprocess");
94 auto& postp = ctx.Get<audio::asr::Postprocess&>("postprocess");
95
96 /* Set default reduction axis for post-processing. */
97 const uint32_t reductionAxis = arm::app::Wav2LetterModel::ms_outputRowsIdx;
98
99 /* Audio clip start index. */
100 auto startClipIdx = ctx.Get<uint32_t>("clipIndex");
101
102 /* Loop to process audio clips. */
103 do {
104 /* Get current audio clip index. */
105 auto currentIndex = ctx.Get<uint32_t>("clipIndex");
106
107 /* Get the current audio buffer and respective size. */
108 const int16_t* audioArr = get_audio_array(currentIndex);
109 const uint32_t audioArrSize = get_audio_array_size(currentIndex);
110
111 if (!audioArr) {
112 printf_err("Invalid audio array pointer\n");
113 return false;
114 }
115
116 /* Audio clip must have enough samples to produce 1 MFCC feature. */
117 if (audioArrSize < mfccParamsWinLen) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100118 printf_err("Not enough audio samples, minimum needed is %" PRIu32 "\n",
119 mfccParamsWinLen);
alexander3c798932021-03-26 21:42:19 +0000120 return false;
121 }
122
123 /* Initialise an audio slider. */
alexander80eecfb2021-07-06 19:47:59 +0100124 auto audioDataSlider = audio::FractionalSlidingWindow<const int16_t>(
alexander3c798932021-03-26 21:42:19 +0000125 audioArr,
126 audioArrSize,
127 audioParamsWinLen,
128 audioParamsWinStride);
129
130 /* Declare a container for results. */
131 std::vector<arm::app::asr::AsrResult> results;
132
133 /* Display message on the LCD - inference running. */
134 std::string str_inf{"Running inference... "};
135 platform.data_psn->present_data_text(
136 str_inf.c_str(), str_inf.size(),
137 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
138
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100139 info("Running inference on audio clip %" PRIu32 " => %s\n", currentIndex,
alexander3c798932021-03-26 21:42:19 +0000140 get_filename(currentIndex));
141
142 size_t inferenceWindowLen = audioParamsWinLen;
143
144 /* Start sliding through audio clip. */
145 while (audioDataSlider.HasNext()) {
146
147 /* If not enough audio see how much can be sent for processing. */
148 size_t nextStartIndex = audioDataSlider.NextWindowStartIndex();
149 if (nextStartIndex + audioParamsWinLen > audioArrSize) {
150 inferenceWindowLen = audioArrSize - nextStartIndex;
151 }
152
153 const int16_t* inferenceWindow = audioDataSlider.Next();
154
155 info("Inference %zu/%zu\n", audioDataSlider.Index() + 1,
156 static_cast<size_t>(ceilf(audioDataSlider.FractionalTotalStrides() + 1)));
157
alexander3c798932021-03-26 21:42:19 +0000158 /* Calculate MFCCs, deltas and populate the input tensor. */
159 prep.Invoke(inferenceWindow, inferenceWindowLen, inputTensor);
160
alexander3c798932021-03-26 21:42:19 +0000161 /* Run inference over this audio clip sliding window. */
alexander27b62d92021-05-04 20:46:08 +0100162 if (!RunInference(model, profiler)) {
163 return false;
164 }
alexander3c798932021-03-26 21:42:19 +0000165
166 /* Post-process. */
167 postp.Invoke(outputTensor, reductionAxis, !audioDataSlider.HasNext());
168
169 /* Get results. */
170 std::vector<ClassificationResult> classificationResult;
171 auto& classifier = ctx.Get<AsrClassifier&>("classifier");
172 classifier.GetClassificationResults(
173 outputTensor, classificationResult,
174 ctx.Get<std::vector<std::string>&>("labels"), 1);
175
176 results.emplace_back(asr::AsrResult(classificationResult,
177 (audioDataSlider.Index() *
178 audioParamsSecondsPerSample *
179 audioParamsWinStride),
180 audioDataSlider.Index(), scoreThreshold));
181
182#if VERIFY_TEST_OUTPUT
183 arm::app::DumpTensor(outputTensor,
184 outputTensor->dims->data[arm::app::Wav2LetterModel::ms_outputColsIdx]);
185#endif /* VERIFY_TEST_OUTPUT */
186
187 }
188
189 /* Erase. */
190 str_inf = std::string(str_inf.size(), ' ');
191 platform.data_psn->present_data_text(
192 str_inf.c_str(), str_inf.size(),
193 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
194
195 ctx.Set<std::vector<arm::app::asr::AsrResult>>("results", results);
196
alexanderc350cdc2021-04-29 20:36:09 +0100197 if (!PresentInferenceResult(platform, results)) {
alexander3c798932021-03-26 21:42:19 +0000198 return false;
199 }
200
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100201 profiler.PrintProfilingResult();
202
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100203 IncrementAppCtxIfmIdx(ctx,"clipIndex");
alexander3c798932021-03-26 21:42:19 +0000204
205 } while (runAll && ctx.Get<uint32_t>("clipIndex") != startClipIdx);
206
207 return true;
208 }
209
alexander3c798932021-03-26 21:42:19 +0000210
alexanderc350cdc2021-04-29 20:36:09 +0100211 static bool PresentInferenceResult(hal_platform& platform,
212 const std::vector<arm::app::asr::AsrResult>& results)
alexander3c798932021-03-26 21:42:19 +0000213 {
214 constexpr uint32_t dataPsnTxtStartX1 = 20;
215 constexpr uint32_t dataPsnTxtStartY1 = 60;
216 constexpr bool allow_multiple_lines = true;
217
218 platform.data_psn->set_text_color(COLOR_GREEN);
219
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100220 info("Final results:\n");
221 info("Total number of inferences: %zu\n", results.size());
alexander3c798932021-03-26 21:42:19 +0000222 /* Results from multiple inferences should be combined before processing. */
223 std::vector<arm::app::ClassificationResult> combinedResults;
224 for (auto& result : results) {
225 combinedResults.insert(combinedResults.end(),
226 result.m_resultVec.begin(),
227 result.m_resultVec.end());
228 }
229
230 /* Get each inference result string using the decoder. */
231 for (const auto & result : results) {
232 std::string infResultStr = audio::asr::DecodeOutput(result.m_resultVec);
233
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100234 info("For timestamp: %f (inference #: %" PRIu32 "); label: %s\n",
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100235 result.m_timeStamp, result.m_inferenceNumber,
236 infResultStr.c_str());
alexander3c798932021-03-26 21:42:19 +0000237 }
238
239 /* Get the decoded result for the combined result. */
240 std::string finalResultStr = audio::asr::DecodeOutput(combinedResults);
241
242 platform.data_psn->present_data_text(
243 finalResultStr.c_str(), finalResultStr.size(),
244 dataPsnTxtStartX1, dataPsnTxtStartY1,
245 allow_multiple_lines);
246
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100247 info("Complete recognition: %s\n", finalResultStr.c_str());
alexander3c798932021-03-26 21:42:19 +0000248 return true;
249 }
250
251} /* namespace app */
252} /* namespace arm */