blob: 7fe959b4c6e13814d0f49a1fe1b94b33612916b3 [file] [log] [blame]
alexander3c798932021-03-26 21:42:19 +00001/*
Richard Burtoned35a6f2022-02-14 11:55:35 +00002 * Copyright (c) 2021-2022 Arm Limited. All rights reserved.
alexander3c798932021-03-26 21:42:19 +00003 * 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"
alexander3c798932021-03-26 21:42:19 +000023#include "AudioUtils.hpp"
Richard Burtoned35a6f2022-02-14 11:55:35 +000024#include "ImageUtils.hpp"
alexander3c798932021-03-26 21:42:19 +000025#include "UseCaseCommonUtils.hpp"
26#include "AsrResult.hpp"
27#include "Wav2LetterPreprocess.hpp"
28#include "Wav2LetterPostprocess.hpp"
29#include "OutputDecode.hpp"
alexander31ae9f02022-02-10 16:15:54 +000030#include "log_macros.h"
alexander3c798932021-03-26 21:42:19 +000031
32namespace arm {
33namespace app {
34
35 /**
Richard Burtonc2911442022-04-22 09:08:21 +010036 * @brief Presents ASR inference results.
37 * @param[in] results Vector of ASR classification results to be displayed.
alexander3c798932021-03-26 21:42:19 +000038 * @return true if successful, false otherwise.
39 **/
Richard Burtonc2911442022-04-22 09:08:21 +010040 static bool PresentInferenceResult(const std::vector<asr::AsrResult>& results);
alexander3c798932021-03-26 21:42:19 +000041
Richard Burtonc2911442022-04-22 09:08:21 +010042 /* ASR inference handler. */
alexander3c798932021-03-26 21:42:19 +000043 bool ClassifyAudioHandler(ApplicationContext& ctx, uint32_t clipIndex, bool runAll)
44 {
Richard Burtonc2911442022-04-22 09:08:21 +010045 auto& model = ctx.Get<Model&>("model");
Isabella Gottardi8df12f32021-04-07 17:15:31 +010046 auto& profiler = ctx.Get<Profiler&>("profiler");
Richard Burtonc2911442022-04-22 09:08:21 +010047 auto mfccFrameLen = ctx.Get<uint32_t>("frameLength");
48 auto mfccFrameStride = ctx.Get<uint32_t>("frameStride");
49 auto scoreThreshold = ctx.Get<float>("scoreThreshold");
50 auto inputCtxLen = ctx.Get<uint32_t>("ctxLen");
alexander3c798932021-03-26 21:42:19 +000051 /* If the request has a valid size, set the audio index. */
52 if (clipIndex < NUMBER_OF_FILES) {
Éanna Ó Catháin8f958872021-09-15 09:32:30 +010053 if (!SetAppCtxIfmIdx(ctx, clipIndex,"clipIndex")) {
alexander3c798932021-03-26 21:42:19 +000054 return false;
55 }
56 }
Richard Burtonc2911442022-04-22 09:08:21 +010057 auto initialClipIdx = ctx.Get<uint32_t>("clipIndex");
58 constexpr uint32_t dataPsnTxtInfStartX = 20;
59 constexpr uint32_t dataPsnTxtInfStartY = 40;
alexander3c798932021-03-26 21:42:19 +000060
alexander3c798932021-03-26 21:42:19 +000061 if (!model.IsInited()) {
62 printf_err("Model is not initialised! Terminating processing.\n");
63 return false;
64 }
65
Richard Burtonc2911442022-04-22 09:08:21 +010066 /* Get input shape. Dimensions of the tensor should have been verified by
alexander3c798932021-03-26 21:42:19 +000067 * the callee. */
Richard Burtonc2911442022-04-22 09:08:21 +010068 TfLiteIntArray* inputShape = model.GetInputShape(0);
alexander3c798932021-03-26 21:42:19 +000069
Richard Burtonc2911442022-04-22 09:08:21 +010070 const uint32_t inputRowsSize = inputShape->data[Wav2LetterModel::ms_inputRowsIdx];
71 const uint32_t inputInnerLen = inputRowsSize - (2 * inputCtxLen);
alexander3c798932021-03-26 21:42:19 +000072
73 /* Audio data stride corresponds to inputInnerLen feature vectors. */
Richard Burtonc2911442022-04-22 09:08:21 +010074 const uint32_t audioDataWindowLen = (inputRowsSize - 1) * mfccFrameStride + (mfccFrameLen);
75 const uint32_t audioDataWindowStride = inputInnerLen * mfccFrameStride;
alexander3c798932021-03-26 21:42:19 +000076
Richard Burtonc2911442022-04-22 09:08:21 +010077 /* NOTE: This is only used for time stamp calculation. */
78 const float secondsPerSample = (1.0 / audio::Wav2LetterMFCC::ms_defaultSamplingFreq);
alexander3c798932021-03-26 21:42:19 +000079
Richard Burtonc2911442022-04-22 09:08:21 +010080 /* Set up pre and post-processing objects. */
81 ASRPreProcess preProcess = ASRPreProcess(model.GetInputTensor(0), Wav2LetterModel::ms_numMfccFeatures,
82 inputShape->data[Wav2LetterModel::ms_inputRowsIdx], mfccFrameLen, mfccFrameStride);
alexander3c798932021-03-26 21:42:19 +000083
Richard Burtonc2911442022-04-22 09:08:21 +010084 std::vector<ClassificationResult> singleInfResult;
85 const uint32_t outputCtxLen = ASRPostProcess::GetOutputContextLen(model, inputCtxLen);
86 ASRPostProcess postProcess = ASRPostProcess(ctx.Get<AsrClassifier&>("classifier"),
87 model.GetOutputTensor(0), ctx.Get<std::vector<std::string>&>("labels"),
88 singleInfResult, outputCtxLen,
89 Wav2LetterModel::ms_blankTokenIdx, Wav2LetterModel::ms_outputRowsIdx
90 );
91
92 UseCaseRunner runner = UseCaseRunner(&preProcess, &postProcess, &model);
alexander3c798932021-03-26 21:42:19 +000093
94 /* Loop to process audio clips. */
95 do {
Kshitij Sisodia68fdd112022-04-06 13:03:20 +010096 hal_lcd_clear(COLOR_BLACK);
Richard Burton9b8d67a2021-12-10 12:32:51 +000097
alexander3c798932021-03-26 21:42:19 +000098 /* Get current audio clip index. */
99 auto currentIndex = ctx.Get<uint32_t>("clipIndex");
100
101 /* Get the current audio buffer and respective size. */
102 const int16_t* audioArr = get_audio_array(currentIndex);
103 const uint32_t audioArrSize = get_audio_array_size(currentIndex);
104
105 if (!audioArr) {
Richard Burtonc2911442022-04-22 09:08:21 +0100106 printf_err("Invalid audio array pointer.\n");
alexander3c798932021-03-26 21:42:19 +0000107 return false;
108 }
109
Richard Burtonc2911442022-04-22 09:08:21 +0100110 /* Audio clip needs enough samples to produce at least 1 MFCC feature. */
111 if (audioArrSize < mfccFrameLen) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100112 printf_err("Not enough audio samples, minimum needed is %" PRIu32 "\n",
Richard Burtonc2911442022-04-22 09:08:21 +0100113 mfccFrameLen);
alexander3c798932021-03-26 21:42:19 +0000114 return false;
115 }
116
Richard Burtonc2911442022-04-22 09:08:21 +0100117 /* Creating a sliding window through the whole audio clip. */
alexander80eecfb2021-07-06 19:47:59 +0100118 auto audioDataSlider = audio::FractionalSlidingWindow<const int16_t>(
Richard Burtonc2911442022-04-22 09:08:21 +0100119 audioArr, audioArrSize,
120 audioDataWindowLen, audioDataWindowStride);
alexander3c798932021-03-26 21:42:19 +0000121
Richard Burtonc2911442022-04-22 09:08:21 +0100122 /* Declare a container for final results. */
123 std::vector<asr::AsrResult> finalResults;
alexander3c798932021-03-26 21:42:19 +0000124
125 /* Display message on the LCD - inference running. */
126 std::string str_inf{"Running inference... "};
Richard Burtonc2911442022-04-22 09:08:21 +0100127 hal_lcd_display_text(str_inf.c_str(), str_inf.size(),
128 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
alexander3c798932021-03-26 21:42:19 +0000129
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100130 info("Running inference on audio clip %" PRIu32 " => %s\n", currentIndex,
alexander3c798932021-03-26 21:42:19 +0000131 get_filename(currentIndex));
132
Richard Burtonc2911442022-04-22 09:08:21 +0100133 size_t inferenceWindowLen = audioDataWindowLen;
alexander3c798932021-03-26 21:42:19 +0000134
135 /* Start sliding through audio clip. */
136 while (audioDataSlider.HasNext()) {
137
Richard Burtonc2911442022-04-22 09:08:21 +0100138 /* If not enough audio, see how much can be sent for processing. */
alexander3c798932021-03-26 21:42:19 +0000139 size_t nextStartIndex = audioDataSlider.NextWindowStartIndex();
Richard Burtonc2911442022-04-22 09:08:21 +0100140 if (nextStartIndex + audioDataWindowLen > audioArrSize) {
alexander3c798932021-03-26 21:42:19 +0000141 inferenceWindowLen = audioArrSize - nextStartIndex;
142 }
143
144 const int16_t* inferenceWindow = audioDataSlider.Next();
145
146 info("Inference %zu/%zu\n", audioDataSlider.Index() + 1,
147 static_cast<size_t>(ceilf(audioDataSlider.FractionalTotalStrides() + 1)));
148
Richard Burtonc2911442022-04-22 09:08:21 +0100149 /* Run the pre-processing, inference and post-processing. */
150 runner.PreProcess(inferenceWindow, inferenceWindowLen);
alexander3c798932021-03-26 21:42:19 +0000151
Richard Burtonc2911442022-04-22 09:08:21 +0100152 profiler.StartProfiling("Inference");
153 if (!runner.RunInference()) {
154 return false;
155 }
156 profiler.StopProfiling();
157
158 postProcess.m_lastIteration = !audioDataSlider.HasNext();
159 if (!runner.PostProcess()) {
alexander27b62d92021-05-04 20:46:08 +0100160 return false;
161 }
alexander3c798932021-03-26 21:42:19 +0000162
Richard Burtonc2911442022-04-22 09:08:21 +0100163 /* Add results from this window to our final results vector. */
164 finalResults.emplace_back(asr::AsrResult(singleInfResult,
165 (audioDataSlider.Index() * secondsPerSample * audioDataWindowStride),
166 audioDataSlider.Index(), scoreThreshold));
alexander3c798932021-03-26 21:42:19 +0000167
168#if VERIFY_TEST_OUTPUT
Richard Burtonc2911442022-04-22 09:08:21 +0100169 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
170 armDumpTensor(outputTensor,
171 outputTensor->dims->data[Wav2LetterModel::ms_outputColsIdx]);
alexander3c798932021-03-26 21:42:19 +0000172#endif /* VERIFY_TEST_OUTPUT */
Richard Burtonc2911442022-04-22 09:08:21 +0100173 } /* while (audioDataSlider.HasNext()) */
alexander3c798932021-03-26 21:42:19 +0000174
175 /* Erase. */
176 str_inf = std::string(str_inf.size(), ' ');
Richard Burtonc2911442022-04-22 09:08:21 +0100177 hal_lcd_display_text(str_inf.c_str(), str_inf.size(),
178 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
alexander3c798932021-03-26 21:42:19 +0000179
Richard Burtonc2911442022-04-22 09:08:21 +0100180 ctx.Set<std::vector<asr::AsrResult>>("results", finalResults);
alexander3c798932021-03-26 21:42:19 +0000181
Richard Burtonc2911442022-04-22 09:08:21 +0100182 if (!PresentInferenceResult(finalResults)) {
alexander3c798932021-03-26 21:42:19 +0000183 return false;
184 }
185
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100186 profiler.PrintProfilingResult();
187
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100188 IncrementAppCtxIfmIdx(ctx,"clipIndex");
alexander3c798932021-03-26 21:42:19 +0000189
Richard Burtonc2911442022-04-22 09:08:21 +0100190 } while (runAll && ctx.Get<uint32_t>("clipIndex") != initialClipIdx);
alexander3c798932021-03-26 21:42:19 +0000191
192 return true;
193 }
194
alexander3c798932021-03-26 21:42:19 +0000195
Richard Burtonc2911442022-04-22 09:08:21 +0100196 static bool PresentInferenceResult(const std::vector<asr::AsrResult>& results)
alexander3c798932021-03-26 21:42:19 +0000197 {
198 constexpr uint32_t dataPsnTxtStartX1 = 20;
199 constexpr uint32_t dataPsnTxtStartY1 = 60;
200 constexpr bool allow_multiple_lines = true;
201
Kshitij Sisodia68fdd112022-04-06 13:03:20 +0100202 hal_lcd_set_text_color(COLOR_GREEN);
alexander3c798932021-03-26 21:42:19 +0000203
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100204 info("Final results:\n");
205 info("Total number of inferences: %zu\n", results.size());
alexander3c798932021-03-26 21:42:19 +0000206 /* Results from multiple inferences should be combined before processing. */
Richard Burtonc2911442022-04-22 09:08:21 +0100207 std::vector<ClassificationResult> combinedResults;
208 for (const auto& result : results) {
alexander3c798932021-03-26 21:42:19 +0000209 combinedResults.insert(combinedResults.end(),
210 result.m_resultVec.begin(),
211 result.m_resultVec.end());
212 }
213
214 /* Get each inference result string using the decoder. */
Richard Burtonc2911442022-04-22 09:08:21 +0100215 for (const auto& result : results) {
alexander3c798932021-03-26 21:42:19 +0000216 std::string infResultStr = audio::asr::DecodeOutput(result.m_resultVec);
217
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100218 info("For timestamp: %f (inference #: %" PRIu32 "); label: %s\n",
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100219 result.m_timeStamp, result.m_inferenceNumber,
220 infResultStr.c_str());
alexander3c798932021-03-26 21:42:19 +0000221 }
222
223 /* Get the decoded result for the combined result. */
224 std::string finalResultStr = audio::asr::DecodeOutput(combinedResults);
225
Richard Burtonc2911442022-04-22 09:08:21 +0100226 hal_lcd_display_text(finalResultStr.c_str(), finalResultStr.size(),
227 dataPsnTxtStartX1, dataPsnTxtStartY1,
228 allow_multiple_lines);
alexander3c798932021-03-26 21:42:19 +0000229
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100230 info("Complete recognition: %s\n", finalResultStr.c_str());
alexander3c798932021-03-26 21:42:19 +0000231 return true;
232 }
233
234} /* namespace app */
235} /* namespace arm */