Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Fix audio trimming of partial detection windows (#1374) (#1375)

Hua.T084a1eca4d29
diff --git a/src/python/txtai/pipeline/audio/signal.py b/src/python/txtai/pipeline/audio/signal.py
index adda6628..a3e0a245 100644
--- a/src/python/txtai/pipeline/audio/signal.py
+++ b/src/python/txtai/pipeline/audio/signal.py
@@ -169,11 +169,15 @@ class Signal:
audio with silence removed
"""
- # Process in 20ms chunks
+ # Empty audio has no chunks to concatenate.
+ if len(audio) == 0:
+ return audio
+
+ # Process in chunks, including the final partial chunk
n, offset = int(rate * (20 / 1000.0) * 2), 0
chunks = []
- while offset + n <= len(audio):
+ while offset < len(audio):
# Calculate energy for chunk and detection result
chunk = audio[offset : offset + n]
energyfreq = Signal.energy(chunk, rate)
diff --git a/test/python/testpipeline/testaudio/testsignal.py b/test/python/testpipeline/testaudio/testsignal.py
new file mode 100644
index 00000000..51a9153a
--- /dev/null
+++ b/test/python/testpipeline/testaudio/testsignal.py
@@ -0,0 +1,33 @@
+"""
+Signal module tests
+"""
+
+import unittest
+
+import numpy as np
+
+from txtai.pipeline.audio.signal import Signal
+
+
+class TestSignal(unittest.TestCase):
+ """
+ Signal tests.
+ """
+
+ def testTrimPartialWindow(self):
+ """
+ Test that short inputs and partial windows are not lost when trimming
+ """
+
+ # At 1000 Hz the detection window has 40 samples.
+ pattern = np.array([1.0, -1.0], dtype=np.float32)
+ for size in (0, 20, 43, 83):
+ audio = np.resize(pattern, size)
+ for trailing in (False, True):
+ with self.subTest(size=size, trailing=trailing):
+ np.testing.assert_array_equal(Signal.trim(audio, 1000, trailing=trailing), audio)
+
+ # Leading silence is still removed while the partial tail is retained.
+ audio = np.resize(pattern, 83)
+ padded = np.concatenate((np.zeros(40, dtype=np.float32), audio))
+ np.testing.assert_array_equal(Signal.trim(padded, 1000, trailing=False), audio)