blob: 76409b6b11a9f09ff4e3c78f6c27b7d0cd8d6410 [file] [log] [blame]
alexander3c798932021-03-26 21:42:19 +00001/*
Richard Burtonf32a86a2022-11-15 11:46:11 +00002 * SPDX-FileCopyrightText: Copyright 2021-2022 Arm Limited and/or its affiliates <open-source-office@arm.com>
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 Burtonb40ecf82022-04-22 16:14:57 +010036 * @brief Presents ASR inference results.
37 * @param[in] results Vector of ASR classification results to be displayed.
38 * @return true if successful, false otherwise.
alexander3c798932021-03-26 21:42:19 +000039 **/
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 Burtonb40ecf82022-04-22 16:14:57 +010066 TfLiteTensor* inputTensor = model.GetInputTensor(0);
67 TfLiteTensor* outputTensor = model.GetOutputTensor(0);
68
Richard Burtonc2911442022-04-22 09:08:21 +010069 /* Get input shape. Dimensions of the tensor should have been verified by
alexander3c798932021-03-26 21:42:19 +000070 * the callee. */
Richard Burtonc2911442022-04-22 09:08:21 +010071 TfLiteIntArray* inputShape = model.GetInputShape(0);
alexander3c798932021-03-26 21:42:19 +000072
Richard Burtonc2911442022-04-22 09:08:21 +010073 const uint32_t inputRowsSize = inputShape->data[Wav2LetterModel::ms_inputRowsIdx];
74 const uint32_t inputInnerLen = inputRowsSize - (2 * inputCtxLen);
alexander3c798932021-03-26 21:42:19 +000075
76 /* Audio data stride corresponds to inputInnerLen feature vectors. */
Richard Burtonc2911442022-04-22 09:08:21 +010077 const uint32_t audioDataWindowLen = (inputRowsSize - 1) * mfccFrameStride + (mfccFrameLen);
78 const uint32_t audioDataWindowStride = inputInnerLen * mfccFrameStride;
alexander3c798932021-03-26 21:42:19 +000079
Richard Burtonc2911442022-04-22 09:08:21 +010080 /* NOTE: This is only used for time stamp calculation. */
81 const float secondsPerSample = (1.0 / audio::Wav2LetterMFCC::ms_defaultSamplingFreq);
alexander3c798932021-03-26 21:42:19 +000082
Richard Burtonc2911442022-04-22 09:08:21 +010083 /* Set up pre and post-processing objects. */
Richard Burtonb40ecf82022-04-22 16:14:57 +010084 AsrPreProcess preProcess = AsrPreProcess(inputTensor, Wav2LetterModel::ms_numMfccFeatures,
85 inputShape->data[Wav2LetterModel::ms_inputRowsIdx],
86 mfccFrameLen, mfccFrameStride);
alexander3c798932021-03-26 21:42:19 +000087
Richard Burtonc2911442022-04-22 09:08:21 +010088 std::vector<ClassificationResult> singleInfResult;
Richard Burtonb40ecf82022-04-22 16:14:57 +010089 const uint32_t outputCtxLen = AsrPostProcess::GetOutputContextLen(model, inputCtxLen);
90 AsrPostProcess postProcess = AsrPostProcess(
91 outputTensor, ctx.Get<AsrClassifier&>("classifier"),
92 ctx.Get<std::vector<std::string>&>("labels"),
Richard Burtonc2911442022-04-22 09:08:21 +010093 singleInfResult, outputCtxLen,
94 Wav2LetterModel::ms_blankTokenIdx, Wav2LetterModel::ms_outputRowsIdx
95 );
96
alexander3c798932021-03-26 21:42:19 +000097 /* Loop to process audio clips. */
98 do {
Kshitij Sisodia68fdd112022-04-06 13:03:20 +010099 hal_lcd_clear(COLOR_BLACK);
Richard Burton9b8d67a2021-12-10 12:32:51 +0000100
alexander3c798932021-03-26 21:42:19 +0000101 /* Get current audio clip index. */
102 auto currentIndex = ctx.Get<uint32_t>("clipIndex");
103
104 /* Get the current audio buffer and respective size. */
105 const int16_t* audioArr = get_audio_array(currentIndex);
106 const uint32_t audioArrSize = get_audio_array_size(currentIndex);
107
108 if (!audioArr) {
Richard Burtonc2911442022-04-22 09:08:21 +0100109 printf_err("Invalid audio array pointer.\n");
alexander3c798932021-03-26 21:42:19 +0000110 return false;
111 }
112
Richard Burtonc2911442022-04-22 09:08:21 +0100113 /* Audio clip needs enough samples to produce at least 1 MFCC feature. */
114 if (audioArrSize < mfccFrameLen) {
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100115 printf_err("Not enough audio samples, minimum needed is %" PRIu32 "\n",
Richard Burtonc2911442022-04-22 09:08:21 +0100116 mfccFrameLen);
alexander3c798932021-03-26 21:42:19 +0000117 return false;
118 }
119
Richard Burtonc2911442022-04-22 09:08:21 +0100120 /* Creating a sliding window through the whole audio clip. */
alexander80eecfb2021-07-06 19:47:59 +0100121 auto audioDataSlider = audio::FractionalSlidingWindow<const int16_t>(
Richard Burtonc2911442022-04-22 09:08:21 +0100122 audioArr, audioArrSize,
123 audioDataWindowLen, audioDataWindowStride);
alexander3c798932021-03-26 21:42:19 +0000124
Richard Burtonc2911442022-04-22 09:08:21 +0100125 /* Declare a container for final results. */
126 std::vector<asr::AsrResult> finalResults;
alexander3c798932021-03-26 21:42:19 +0000127
128 /* Display message on the LCD - inference running. */
129 std::string str_inf{"Running inference... "};
Richard Burtonc2911442022-04-22 09:08:21 +0100130 hal_lcd_display_text(str_inf.c_str(), str_inf.size(),
131 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
alexander3c798932021-03-26 21:42:19 +0000132
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100133 info("Running inference on audio clip %" PRIu32 " => %s\n", currentIndex,
alexander3c798932021-03-26 21:42:19 +0000134 get_filename(currentIndex));
135
Richard Burtonc2911442022-04-22 09:08:21 +0100136 size_t inferenceWindowLen = audioDataWindowLen;
alexander3c798932021-03-26 21:42:19 +0000137
138 /* Start sliding through audio clip. */
139 while (audioDataSlider.HasNext()) {
140
Richard Burtonc2911442022-04-22 09:08:21 +0100141 /* If not enough audio, see how much can be sent for processing. */
alexander3c798932021-03-26 21:42:19 +0000142 size_t nextStartIndex = audioDataSlider.NextWindowStartIndex();
Richard Burtonc2911442022-04-22 09:08:21 +0100143 if (nextStartIndex + audioDataWindowLen > audioArrSize) {
alexander3c798932021-03-26 21:42:19 +0000144 inferenceWindowLen = audioArrSize - nextStartIndex;
145 }
146
147 const int16_t* inferenceWindow = audioDataSlider.Next();
148
149 info("Inference %zu/%zu\n", audioDataSlider.Index() + 1,
150 static_cast<size_t>(ceilf(audioDataSlider.FractionalTotalStrides() + 1)));
151
Richard Burtonc2911442022-04-22 09:08:21 +0100152 /* Run the pre-processing, inference and post-processing. */
Richard Burtonb40ecf82022-04-22 16:14:57 +0100153 if (!preProcess.DoPreProcess(inferenceWindow, inferenceWindowLen)) {
154 printf_err("Pre-processing failed.");
Richard Burtonc2911442022-04-22 09:08:21 +0100155 return false;
156 }
Richard Burtonc2911442022-04-22 09:08:21 +0100157
Richard Burtonb40ecf82022-04-22 16:14:57 +0100158 if (!RunInference(model, profiler)) {
159 printf_err("Inference failed.");
160 return false;
161 }
162
163 /* Post processing needs to know if we are on the last audio window. */
Richard Burtonc2911442022-04-22 09:08:21 +0100164 postProcess.m_lastIteration = !audioDataSlider.HasNext();
Richard Burtonb40ecf82022-04-22 16:14:57 +0100165 if (!postProcess.DoPostProcess()) {
166 printf_err("Post-processing failed.");
alexander27b62d92021-05-04 20:46:08 +0100167 return false;
168 }
alexander3c798932021-03-26 21:42:19 +0000169
Richard Burtonc2911442022-04-22 09:08:21 +0100170 /* Add results from this window to our final results vector. */
171 finalResults.emplace_back(asr::AsrResult(singleInfResult,
172 (audioDataSlider.Index() * secondsPerSample * audioDataWindowStride),
173 audioDataSlider.Index(), scoreThreshold));
alexander3c798932021-03-26 21:42:19 +0000174
175#if VERIFY_TEST_OUTPUT
Richard Burtonc2911442022-04-22 09:08:21 +0100176 armDumpTensor(outputTensor,
177 outputTensor->dims->data[Wav2LetterModel::ms_outputColsIdx]);
alexander3c798932021-03-26 21:42:19 +0000178#endif /* VERIFY_TEST_OUTPUT */
Richard Burtonc2911442022-04-22 09:08:21 +0100179 } /* while (audioDataSlider.HasNext()) */
alexander3c798932021-03-26 21:42:19 +0000180
181 /* Erase. */
182 str_inf = std::string(str_inf.size(), ' ');
Richard Burtonc2911442022-04-22 09:08:21 +0100183 hal_lcd_display_text(str_inf.c_str(), str_inf.size(),
184 dataPsnTxtInfStartX, dataPsnTxtInfStartY, 0);
alexander3c798932021-03-26 21:42:19 +0000185
Richard Burtonc2911442022-04-22 09:08:21 +0100186 ctx.Set<std::vector<asr::AsrResult>>("results", finalResults);
alexander3c798932021-03-26 21:42:19 +0000187
Richard Burtonc2911442022-04-22 09:08:21 +0100188 if (!PresentInferenceResult(finalResults)) {
alexander3c798932021-03-26 21:42:19 +0000189 return false;
190 }
191
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100192 profiler.PrintProfilingResult();
193
Éanna Ó Catháin8f958872021-09-15 09:32:30 +0100194 IncrementAppCtxIfmIdx(ctx,"clipIndex");
alexander3c798932021-03-26 21:42:19 +0000195
Richard Burtonc2911442022-04-22 09:08:21 +0100196 } while (runAll && ctx.Get<uint32_t>("clipIndex") != initialClipIdx);
alexander3c798932021-03-26 21:42:19 +0000197
198 return true;
199 }
200
alexander3c798932021-03-26 21:42:19 +0000201
Richard Burtonc2911442022-04-22 09:08:21 +0100202 static bool PresentInferenceResult(const std::vector<asr::AsrResult>& results)
alexander3c798932021-03-26 21:42:19 +0000203 {
204 constexpr uint32_t dataPsnTxtStartX1 = 20;
205 constexpr uint32_t dataPsnTxtStartY1 = 60;
206 constexpr bool allow_multiple_lines = true;
207
Kshitij Sisodia68fdd112022-04-06 13:03:20 +0100208 hal_lcd_set_text_color(COLOR_GREEN);
alexander3c798932021-03-26 21:42:19 +0000209
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100210 info("Final results:\n");
211 info("Total number of inferences: %zu\n", results.size());
alexander3c798932021-03-26 21:42:19 +0000212 /* Results from multiple inferences should be combined before processing. */
Richard Burtonc2911442022-04-22 09:08:21 +0100213 std::vector<ClassificationResult> combinedResults;
214 for (const auto& result : results) {
alexander3c798932021-03-26 21:42:19 +0000215 combinedResults.insert(combinedResults.end(),
216 result.m_resultVec.begin(),
217 result.m_resultVec.end());
218 }
219
220 /* Get each inference result string using the decoder. */
Richard Burtonc2911442022-04-22 09:08:21 +0100221 for (const auto& result : results) {
alexander3c798932021-03-26 21:42:19 +0000222 std::string infResultStr = audio::asr::DecodeOutput(result.m_resultVec);
223
Kshitij Sisodiaf9c19ea2021-05-07 16:08:14 +0100224 info("For timestamp: %f (inference #: %" PRIu32 "); label: %s\n",
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100225 result.m_timeStamp, result.m_inferenceNumber,
226 infResultStr.c_str());
alexander3c798932021-03-26 21:42:19 +0000227 }
228
229 /* Get the decoded result for the combined result. */
230 std::string finalResultStr = audio::asr::DecodeOutput(combinedResults);
231
Richard Burtonc2911442022-04-22 09:08:21 +0100232 hal_lcd_display_text(finalResultStr.c_str(), finalResultStr.size(),
233 dataPsnTxtStartX1, dataPsnTxtStartY1,
234 allow_multiple_lines);
alexander3c798932021-03-26 21:42:19 +0000235
Isabella Gottardi8df12f32021-04-07 17:15:31 +0100236 info("Complete recognition: %s\n", finalResultStr.c_str());
alexander3c798932021-03-26 21:42:19 +0000237 return true;
238 }
239
240} /* namespace app */
241} /* namespace arm */