diff --git a/.github/actions/clip-export/action.yml b/.github/actions/clip-export/action.yml index a9ebd52..f6c98ad 100644 --- a/.github/actions/clip-export/action.yml +++ b/.github/actions/clip-export/action.yml @@ -20,7 +20,7 @@ runs: shell: bash env: HF_HUB_OFFLINE: "1" - run: python -m pytest -q tests/test_cli_video_clip.py + run: python -m pytest -q tests/test_cli_video_clip.py tests/test_video_recognition_audio.py - name: Test the CLI from both built archives id: archives shell: bash diff --git a/funclip/videoclipper.py b/funclip/videoclipper.py index b6eb174..4137c61 100644 --- a/funclip/videoclipper.py +++ b/funclip/videoclipper.py @@ -249,36 +249,30 @@ def clip(self, dest_text, start_ost, end_ost, state, dest_spk=None, output_dir=N return (sr, res_audio), message, clip_srt def video_recog(self, video_filename, sd_switch='no', hotwords="", output_dir=None): - video = mpy.VideoFileClip(video_filename) - # Extract the base name, add '_clip.mp4', and 'wav' + base_name = os.path.splitext(video_filename)[0] if output_dir is not None: os.makedirs(output_dir, exist_ok=True) - _, base_name = os.path.split(video_filename) - base_name, _ = os.path.splitext(base_name) - clip_video_file = base_name + '_clip.mp4' - audio_file = base_name + '.wav' - audio_file = os.path.join(output_dir, audio_file) - else: - base_name, _ = os.path.splitext(video_filename) - clip_video_file = base_name + '_clip.mp4' - audio_file = base_name + '.wav' - - if video.audio is None: - logging.error("No audio information found.") - sys.exit(1) - - video.audio.write_audiofile(audio_file) - wav = librosa.load(audio_file, sr=16000)[0] - # delete the audio file after processing - if os.path.exists(audio_file): - os.remove(audio_file) - state = { - 'video_filename': video_filename, - 'clip_video_file': clip_video_file, - 'video': video, - } - # res_text, res_srt = self.recog((16000, wav), state) - return self.recog((16000, wav), sd_switch, state, hotwords, output_dir) + base_name = os.path.basename(base_name) + + with ExitStack() as cleanup: + video = mpy.VideoFileClip(video_filename) + cleanup.callback(video.close) + if video.audio is None: + logging.error("No audio information found.") + sys.exit(1) + + with tempfile.TemporaryDirectory(prefix="funclip-audio-") as tmp: + audio_file = os.path.join(tmp, "audio.wav") + video.audio.write_audiofile(audio_file) + wav = librosa.load(audio_file, sr=16000)[0] + state = { + 'video_filename': video_filename, + 'clip_video_file': base_name + '_clip.mp4', + 'video': video, + } + result = self.recog((16000, wav), sd_switch, state, hotwords, output_dir) + cleanup.pop_all() # The returned state keeps the reader for video_clip. + return result def video_clip(self, dest_text, diff --git a/tests/test_video_recognition_audio.py b/tests/test_video_recognition_audio.py new file mode 100644 index 0000000..c5d57df --- /dev/null +++ b/tests/test_video_recognition_audio.py @@ -0,0 +1,77 @@ +import os +import sys +import tempfile +import unittest +import wave +from pathlib import Path +from unittest.mock import Mock, patch + +import numpy as np +from moviepy.editor import AudioClip, ColorClip + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "funclip")) +from videoclipper import VideoClipper + + +class RecognitionAudioTests(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + self.addCleanup(os.chdir, os.getcwd()) + os.chdir(self.root) + self.source = self.root / "source" / "interview.mp4" + self.source.parent.mkdir() + with AudioClip(lambda t: 0.2 * np.sin(2 * np.pi * 440 * t), duration=0.5, fps=44100) as tone: + with ColorClip((32, 24), color=(20, 60, 90), duration=0.5).set_audio(tone) as clip: + clip.write_videofile(str(self.source), fps=10, codec="libx264", audio_codec="aac", + logger=None) + self.model = Mock() + self.model.generate.return_value = [{"text": "hello", "timestamp": [[0, 500]]}] + self.clipper = VideoClipper(self.model) + self.clipper.lang = "en" + + def sidecar(self, directory): + wav = directory / "interview.wav" + with wave.open(str(wav), "wb") as output: + output.setparams((1, 2, 8000, 0, "NONE", "not compressed")) + output.writeframes(b"\x00\x00" * 160) + return wav, wav.read_bytes() + + def check_recognition(self, output_dir=None): + sidecar, original = self.sidecar(output_dir or self.source.parent) + _, _, state = self.clipper.video_recog(str(self.source), output_dir=output_dir) + self.addCleanup(state["video"].close) + self.assertTrue(sidecar.is_file(), "recognition deleted the existing recording") + self.assertEqual(sidecar.read_bytes(), original) + self.assertEqual(state["video"].get_frame(0).shape[:2], (24, 32)) + self.model.generate.assert_called_once() + audio = self.model.generate.call_args.args[0] + self.assertEqual(state["audio_input"][0], 16000) + self.assertTrue(np.isfinite(audio).all()) + peak_hz = np.fft.rfftfreq(len(audio), 1 / 16000)[abs(np.fft.rfft(audio)).argmax()] + self.assertAlmostEqual(peak_hz, 440, delta=5) + + def test_keeps_same_named_recording_next_to_video(self): + self.check_recognition() + + def test_keeps_same_named_recording_in_output_directory(self): + out = self.root / "selected output" + out.mkdir() + self.check_recognition(out) + + def test_decode_failure_discards_only_its_temporary_audio(self): + wav, original = self.sidecar(self.source.parent) + extracted = [] + + def fail(path, *, sr): + extracted.append(Path(path).resolve()) + self.assertTrue(extracted[0].is_file()) + raise RuntimeError("audio read failed") + + with patch("videoclipper.librosa.load", side_effect=fail): + with self.assertRaisesRegex(RuntimeError, "audio read failed"): + self.clipper.video_recog(str(self.source)) + self.assertEqual(wav.read_bytes(), original) + self.assertFalse(extracted[0].exists()) + self.model.generate.assert_not_called()