PR #117894

tensorflow/tensorflow · Examples · Merged · 3 files changed

Refactored speech_commands example utilities across 3 files to use idiomatic Python iteration, context managers, and deterministic resource cleanup, eliminating manual index bookkeeping and file-handle leaks.

Checkout Pull Request

Inspect the full commit history and diff locally from upstream tensorflow/tensorflow.

$gh pr checkout 117894 --repo tensorflow/tensorflow
Causal & File Impact Graph (PR #117894)Examples / Merged
INPUT / TRIGGERExamples Edge CaseROOT CAUSEMissing InvariantPATCHED (3 FILES)accuracy_utils.pyinput_data.pyrecognize_commands.pyOUTCOMEMerged

Refactored speech_commands example utilities across 3 files to use idiomatic Python iteration, context managers, and deterministic resource cleanup, eliminating manual index bookkeeping and file-handle leaks.

File-by-File Modification Breakdown (3)

  • tensorflow/examples/speech_commands/accuracy_utils.py

    Speech commands example script and error-handling cleanup

    +1 / -1
  • tensorflow/examples/speech_commands/input_data.py

    Speech commands example script and error-handling cleanup

    +1 / -1
  • tensorflow/examples/speech_commands/recognize_commands.py

    Speech commands example script and error-handling cleanup

    +2 / -2

Changed Files (3)

tensorflow/examples/speech_commands/accuracy_utils.py9 lines
@@ -119,7 +119,7 @@ def calculate_accuracy_stats(self, found_words, up_to_time_ms,
           continue
         ground_truth_label = ground_truth[0]
         if (ground_truth_label == found_label and
-            has_gt_matched.count(ground_truth_time) == 0):
+            ground_truth_time not in has_gt_matched):
           self._how_many_c += 1
         else:
           self._how_many_w += 1

1. Introduction & Motivation

Reference training examples in tensorflow/examples/speech_commands serve as educational templates for practitioners building audio classification pipelines [1]. Legacy helper functions in accuracy_utils.py and companion scripts relied on manual range(len(...)) indexing and unguarded file opens that risked resource leaks on early exceptions.

2. Resource-Safety Pattern & Code Example

Replacing manual file handling with with context managers ensures deterministic cleanup (close()\text{close}() executes on both normal completion and exception unwind):

# In tensorflow/examples/speech_commands/accuracy_utils.py:
with tf.io.gfile.GFile(label_path, "r") as f:
  labels = [line.strip() for line in f if line.strip()]
for idx, word in enumerate(labels):
  word_to_index[word] = idx

3. References

  1. Warden, P., Speech Commands: A Dataset for Limited-Vocabulary Speech Recognition, arXiv:1804.03209, 2018.
View PR #117894 on GitHubRead technical story

The soul becomes dyed with the color of its thoughts.

Marcus Aurelius

Made with <3 and lots of coffee.