main_functions.cc 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
  2. Licensed under the Apache License, Version 2.0 (the "License");
  3. you may not use this file except in compliance with the License.
  4. You may obtain a copy of the License at
  5. http://www.apache.org/licenses/LICENSE-2.0
  6. Unless required by applicable law or agreed to in writing, software
  7. distributed under the License is distributed on an "AS IS" BASIS,
  8. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  9. See the License for the specific language governing permissions and
  10. limitations under the License.
  11. ==============================================================================*/
  12. #include "tensorflow/lite/micro/examples/micro_speech/main_functions.h"
  13. #include "tensorflow/lite/micro/examples/micro_speech/audio_provider.h"
  14. #include "tensorflow/lite/micro/examples/micro_speech/command_responder.h"
  15. #include "tensorflow/lite/micro/examples/micro_speech/feature_provider.h"
  16. #include "tensorflow/lite/micro/examples/micro_speech/micro_features/micro_model_settings.h"
  17. #include "tensorflow/lite/micro/examples/micro_speech/micro_features/model.h"
  18. #include "tensorflow/lite/micro/examples/micro_speech/recognize_commands.h"
  19. #include "tensorflow/lite/micro/micro_error_reporter.h"
  20. #include "tensorflow/lite/micro/micro_interpreter.h"
  21. #include "tensorflow/lite/micro/micro_mutable_op_resolver.h"
  22. #include "tensorflow/lite/schema/schema_generated.h"
  23. #include "tensorflow/lite/version.h"
  24. // Globals, used for compatibility with Arduino-style sketches.
  25. namespace {
  26. tflite::ErrorReporter* error_reporter = nullptr;
  27. const tflite::Model* model = nullptr;
  28. tflite::MicroInterpreter* interpreter = nullptr;
  29. TfLiteTensor* model_input = nullptr;
  30. FeatureProvider* feature_provider = nullptr;
  31. RecognizeCommands* recognizer = nullptr;
  32. int32_t previous_time = 0;
  33. // Create an area of memory to use for input, output, and intermediate arrays.
  34. // The size of this will depend on the model you're using, and may need to be
  35. // determined by experimentation.
  36. constexpr int kTensorArenaSize = 10 * 1024;
  37. uint8_t tensor_arena[kTensorArenaSize];
  38. int8_t feature_buffer[kFeatureElementCount];
  39. int8_t* model_input_buffer = nullptr;
  40. } // namespace
  41. // The name of this function is important for Arduino compatibility.
  42. void setup() {
  43. // Set up logging. Google style is to avoid globals or statics because of
  44. // lifetime uncertainty, but since this has a trivial destructor it's okay.
  45. // NOLINTNEXTLINE(runtime-global-variables)
  46. static tflite::MicroErrorReporter micro_error_reporter;
  47. error_reporter = &micro_error_reporter;
  48. // Map the model into a usable data structure. This doesn't involve any
  49. // copying or parsing, it's a very lightweight operation.
  50. model = tflite::GetModel(g_model);
  51. if (model->version() != TFLITE_SCHEMA_VERSION) {
  52. TF_LITE_REPORT_ERROR(error_reporter,
  53. "Model provided is schema version %d not equal "
  54. "to supported version %d.",
  55. model->version(), TFLITE_SCHEMA_VERSION);
  56. return;
  57. }
  58. // Pull in only the operation implementations we need.
  59. // This relies on a complete list of all the ops needed by this graph.
  60. // An easier approach is to just use the AllOpsResolver, but this will
  61. // incur some penalty in code space for op implementations that are not
  62. // needed by this graph.
  63. //
  64. // tflite::AllOpsResolver resolver;
  65. // NOLINTNEXTLINE(runtime-global-variables)
  66. static tflite::MicroMutableOpResolver<4> micro_op_resolver(error_reporter);
  67. if (micro_op_resolver.AddDepthwiseConv2D() != kTfLiteOk) {
  68. return;
  69. }
  70. if (micro_op_resolver.AddFullyConnected() != kTfLiteOk) {
  71. return;
  72. }
  73. if (micro_op_resolver.AddSoftmax() != kTfLiteOk) {
  74. return;
  75. }
  76. if (micro_op_resolver.AddReshape() != kTfLiteOk) {
  77. return;
  78. }
  79. // Build an interpreter to run the model with.
  80. static tflite::MicroInterpreter static_interpreter(
  81. model, micro_op_resolver, tensor_arena, kTensorArenaSize, error_reporter);
  82. interpreter = &static_interpreter;
  83. // Allocate memory from the tensor_arena for the model's tensors.
  84. TfLiteStatus allocate_status = interpreter->AllocateTensors();
  85. if (allocate_status != kTfLiteOk) {
  86. TF_LITE_REPORT_ERROR(error_reporter, "AllocateTensors() failed");
  87. return;
  88. }
  89. // Get information about the memory area to use for the model's input.
  90. model_input = interpreter->input(0);
  91. if ((model_input->dims->size != 2) || (model_input->dims->data[0] != 1) ||
  92. (model_input->dims->data[1] !=
  93. (kFeatureSliceCount * kFeatureSliceSize)) ||
  94. (model_input->type != kTfLiteInt8)) {
  95. TF_LITE_REPORT_ERROR(error_reporter,
  96. "Bad input tensor parameters in model");
  97. return;
  98. }
  99. model_input_buffer = model_input->data.int8;
  100. // Prepare to access the audio spectrograms from a microphone or other source
  101. // that will provide the inputs to the neural network.
  102. // NOLINTNEXTLINE(runtime-global-variables)
  103. static FeatureProvider static_feature_provider(kFeatureElementCount,
  104. feature_buffer);
  105. feature_provider = &static_feature_provider;
  106. static RecognizeCommands static_recognizer(error_reporter);
  107. recognizer = &static_recognizer;
  108. previous_time = 0;
  109. }
  110. // The name of this function is important for Arduino compatibility.
  111. void loop() {
  112. // Fetch the spectrogram for the current time.
  113. const int32_t current_time = LatestAudioTimestamp();
  114. int how_many_new_slices = 0;
  115. TfLiteStatus feature_status = feature_provider->PopulateFeatureData(
  116. error_reporter, previous_time, current_time, &how_many_new_slices);
  117. if (feature_status != kTfLiteOk) {
  118. TF_LITE_REPORT_ERROR(error_reporter, "Feature generation failed");
  119. return;
  120. }
  121. previous_time = current_time;
  122. // If no new audio samples have been received since last time, don't bother
  123. // running the network model.
  124. if (how_many_new_slices == 0) {
  125. return;
  126. }
  127. // Copy feature buffer to input tensor
  128. for (int i = 0; i < kFeatureElementCount; i++) {
  129. model_input_buffer[i] = feature_buffer[i];
  130. }
  131. // Run the model on the spectrogram input and make sure it succeeds.
  132. TfLiteStatus invoke_status = interpreter->Invoke();
  133. if (invoke_status != kTfLiteOk) {
  134. TF_LITE_REPORT_ERROR(error_reporter, "Invoke failed");
  135. return;
  136. }
  137. // Obtain a pointer to the output tensor
  138. TfLiteTensor* output = interpreter->output(0);
  139. // Determine whether a command was recognized based on the output of inference
  140. const char* found_command = nullptr;
  141. uint8_t score = 0;
  142. bool is_new_command = false;
  143. TfLiteStatus process_status = recognizer->ProcessLatestResults(
  144. output, current_time, &found_command, &score, &is_new_command);
  145. if (process_status != kTfLiteOk) {
  146. TF_LITE_REPORT_ERROR(error_reporter,
  147. "RecognizeCommands::ProcessLatestResults() failed");
  148. return;
  149. }
  150. // Do something based on the recognized command. The default implementation
  151. // just prints to the error console, but you should replace this with your
  152. // own function for a real application.
  153. RespondToCommand(error_reporter, current_time, found_command, score,
  154. is_new_command);
  155. }