From bff068e4b23088e770643b4b05a6aa18695f31a1 Mon Sep 17 00:00:00 2001 From: zhifu gao Date: Wed, 2 Dec 2026 12:39:31 +0800 Subject: [PATCH] Protect stage-2 audio exports from missing selections and file collisions Do not export the original recording or an empty result when stage 2 selects no samples. Reserve the WAV and SRT destinations together, including default paths, and keep the UI preview fallback unchanged. Signed-off-by: zhifu gao --- .github/actions/clip-export/action.yml | 2 +- README.md | 8 +++ README_zh.md | 8 +++ funclip/videoclipper.py | 65 +++++++++++-------- scripts/verify_release_cli.py | 5 +- tests/test_cli_audio_clip.py | 87 ++++++++++++++++++++++++++ 6 files changed, 147 insertions(+), 28 deletions(-) create mode 100644 tests/test_cli_audio_clip.py diff --git a/.github/actions/clip-export/action.yml b/.github/actions/clip-export/action.yml index f6c98ad..e810ec9 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 tests/test_video_recognition_audio.py + run: python -m pytest -q tests/test_cli_audio_clip.py 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/README.md b/README.md index b386125..00e54df 100644 --- a/README.md +++ b/README.md @@ -180,6 +180,14 @@ python funclip/videoclipper.py --stage 2 \ For this **stage-2 video** command, exit code 0 means both `./output/res.mp4` and `./output/res.srt` were written. Choose a fresh output name: an existing MP4 or SRT is not overwritten when you specify `--output_file`. If no text matches, the command exits nonzero without creating either file. Copy the words from the saved transcript before retrying. +**Clipping an audio file instead (current source):** Run stage 1 on your recording first. Then reuse that same file and state directory. For example, if the recording is `talk.wav` and the saved transcript contains “later”: + +```sh +python funclip/videoclipper.py --stage 2 --lang en --file talk.wav --output_dir ./output --dest_text later --output_file ./output/quote.wav +``` + +This step reads the saved timing; it does not run recognition again. Success writes both `quote.wav` and `quote.srt`. Without `--output_file`, the names are `result.wav` and `result.srt` in the state directory. Neither name may already exist. A missing match or offsets that leave no audio cause a nonzero exit, not an export of the original recording. Check your selection or choose a fresh output name before retrying. + ## Community Communication🍟 diff --git a/README_zh.md b/README_zh.md index cb59f28..aa7c3c5 100644 --- a/README_zh.md +++ b/README_zh.md @@ -171,6 +171,14 @@ python funclip/videoclipper.py --stage 2 \ 这条**第二阶段视频剪辑**命令退出码为 0 时,应同时得到 `./output/res.mp4` 和 `./output/res.srt`。使用 `--output_file` 时请选择新文件名:已有的视频或同名字幕均不会被覆盖。未匹配到文字时,命令以非零状态退出,不生成这两个文件;请先从已保存的转写结果核对选词,再重试。 +**如果要剪音频(当前源码):** 先对自己的录音完成第一阶段识别。第二阶段使用同一份录音和识别结果目录。例如,文件名是 `talk.wav`,保存的转写中有“你好”,可以这样剪: + +```sh +python funclip/videoclipper.py --stage 2 --lang zh --file talk.wav --output_dir ./output --dest_text '你好' --output_file ./output/quote.wav +``` + +这一步读取已保存的时间戳,不会重新识别。成功后会同时得到 `quote.wav` 和 `quote.srt`;不指定输出路径时,则写入识别目录下的 `result.wav` 和 `result.srt`。两个文件名都必须是新的。未匹配到文字或偏移后没有剩余音频时,命令以非零状态退出,不会把原录音当作剪辑结果。请核对所选文字、偏移或输出文件名后再试。 + ### C.通过创空间与Space体验FunClip [FunClip@Modelscope创空间⭐](https://modelscope.cn/studios/iic/funasr_app_clipvideo/summary) diff --git a/funclip/videoclipper.py b/funclip/videoclipper.py index 4137c61..8dfb826 100644 --- a/funclip/videoclipper.py +++ b/funclip/videoclipper.py @@ -175,7 +175,8 @@ def recog(self, audio_input, sd_switch='no', state=None, hotwords="", output_dir state['sentences'] = sentence_info return res_text, res_srt, state - def clip(self, dest_text, start_ost, end_ost, state, dest_spk=None, output_dir=None, timestamp_list=None): + def clip(self, dest_text, start_ost, end_ost, state, dest_spk=None, output_dir=None, timestamp_list=None, + *, require_match=False): # get from state audio_input = state['audio_input'] recog_res_raw = state['recog_res_raw'] @@ -246,6 +247,8 @@ def clip(self, dest_text, start_ost, end_ost, state, dest_spk=None, output_dir=N else: message = "No period found in the speech, return raw speech. You may check the recognition result and try other destination text." + log_append res_audio = data + if require_match and (not len(ts) or not res_audio.size): + return None, "No audio selected. Check the transcript and start/end offsets." + log_append, "" return (sr, res_audio), message, clip_srt def video_recog(self, video_filename, sd_switch='no', hotwords="", output_dir=None): @@ -472,6 +475,39 @@ def get_parser(): return parser +def _publish_clip_pair(media, subtitle, staged_media, staged_subtitle, *, exclusive): + with ExitStack() as rollback: + if exclusive: + for path in (media, subtitle): + try: + path.touch(exist_ok=False) + except FileExistsError: + raise SystemExit(f"Output already exists: {path}") from None + rollback.callback(path.unlink) + os.replace(staged_media, media) + os.replace(staged_subtitle, subtitle) + rollback.pop_all() + + +def _export_cli_audio(clipper, state, output, dest_text, dest_spk, start_ost, end_ost): + if output.suffix.lower() != ".wav": + raise SystemExit("Audio --output_file must end with .wav") + subtitle = output.with_suffix(".srt") + selected, message, srt = clipper.clip( + dest_text, start_ost, end_ost, state, dest_spk=dest_spk, require_match=True) + if selected is None: + raise SystemExit(message) + rate, samples = selected + with tempfile.TemporaryDirectory(dir=output.parent) as tmp: + staged = Path(tmp) / "clip.wav" + sf.write(staged, samples, rate) + staged_srt = staged.with_suffix(".srt") + staged_srt.write_text(srt, encoding="utf-8") + _publish_clip_pair(output, subtitle, staged, staged_srt, exclusive=True) + logging.info("Clipping Log: %s", message) + logging.warning("Saved clipped audio to %s and subtitles to %s", output, subtitle) + + def _export_cli_video(clipper, file, state, output_file, dest_text, dest_spk, start_ost, end_ost): source = Path(file) if output_file is None: @@ -497,19 +533,7 @@ def _export_cli_video(clipper, file, state, output_file, dest_text, dest_spk, st logging.warning("Clipping Log: %s", message) staged_srt = Path(tmp) / "clip.srt" staged_srt.write_text(srt, encoding="utf-8") - with ExitStack() as rollback: - if output_file is not None: - # Reserve both names exclusively, even if another export began - # after the initial check. Roll back only names we created. - for path in (video, subtitle): - try: - path.touch(exist_ok=False) - except FileExistsError: - raise SystemExit(f"Output already exists: {path}") from None - rollback.callback(path.unlink) - os.replace(rendered, video) - os.replace(staged_srt, subtitle) - rollback.pop_all() + _publish_clip_pair(video, subtitle, rendered, staged_srt, exclusive=output_file is not None) logging.warning("Saved clipped video to %s and subtitles to %s", video, subtitle) @@ -569,17 +593,8 @@ def runner(stage, file, sd_switch, output_dir, dest_text, dest_spk, start_ost, e state = load_state(output_dir) wav, sr = librosa.load(file, sr=16000) state['audio_input'] = (sr, wav) - (sr, audio), message, srt_clip = audio_clipper.clip(dest_text, start_ost, end_ost, state, dest_spk=dest_spk) - if output_file is None: - output_file = output_dir + '/result.wav' - clip_srt_file = output_file[:-3] + 'srt' - logging.warning(message) - sf.write(output_file, audio, 16000) - assert output_file.endswith('.wav'), "output_file must ends with '.wav'" - logging.warning("Save clipped wav file to {}".format(output_file)) - with open(clip_srt_file, 'w') as fout: - fout.write(srt_clip) - logging.warning("Write clipped subtitle to {}".format(clip_srt_file)) + output = Path(output_file) if output_file is not None else Path(output_dir) / "result.wav" + _export_cli_audio(audio_clipper, state, output, dest_text, dest_spk, start_ost, end_ost) if mode == 'video': state = load_state(output_dir) _export_cli_video(audio_clipper, file, state, output_file, dest_text, dest_spk, start_ost, end_ost) diff --git a/scripts/verify_release_cli.py b/scripts/verify_release_cli.py index 7786741..84ece0f 100644 --- a/scripts/verify_release_cli.py +++ b/scripts/verify_release_cli.py @@ -12,6 +12,7 @@ ROOT = Path(__file__).resolve().parents[1] TEST = Path("tests/test_cli_video_clip.py") +AUDIO = Path("tests/test_cli_audio_clip.py") SUBTITLES = Path("tests/test_subtitle_renderer.py") CASE = TEST.as_posix() + "::CLIClipTests::test_stage_two_exports_the_selected_video_and_subtitle" @@ -37,12 +38,12 @@ def verify(dist): with tarfile.open(artifact, "r:gz") as archive: archive.extractall(tmp, filter="data") root = Path(tmp) / prefix - for test in (TEST, SUBTITLES): + for test in (TEST, AUDIO, SUBTITLES): if (root / test).read_bytes() != (ROOT / test).read_bytes(): raise ValueError(f"{test} differs from checkout in {artifact.name}") print(f"Testing stage-2 export and subtitle rendering from {artifact.name}", flush=True) subprocess.run([sys.executable, "-I", "-m", "pytest", "-q", "-o", "pythonpath=.", - CASE, SUBTITLES.as_posix()], + CASE, AUDIO.as_posix() + "::test_selected_audio_and_subtitle", SUBTITLES.as_posix()], cwd=root, env=env, check=True, timeout=180) diff --git a/tests/test_cli_audio_clip.py b/tests/test_cli_audio_clip.py new file mode 100644 index 0000000..7d35477 --- /dev/null +++ b/tests/test_cli_audio_clip.py @@ -0,0 +1,87 @@ +import subprocess +import sys +from pathlib import Path + +import numpy as np +import pytest +import soundfile as sf + + +CLI = Path(__file__).resolve().parents[1] / "funclip" / "videoclipper.py" + + +@pytest.fixture +def recording(tmp_path): + samples = np.repeat(np.array([2048, -4096], dtype=np.int16), 16000) + source = tmp_path / "source.wav" + sf.write(source, samples, 16000, subtype="PCM_16") + state = tmp_path / "state" + state.mkdir() + spans = [[0, 1000], [1000, 2000]] + for key, value in { + "recog_res_raw": "early later", + "timestamp": repr(spans), + "sentences": repr([{"text": word, "timestamp": [span]} + for word, span in zip(["early", "later"], spans)]), + }.items(): + (state / key).write_text(value, encoding="utf-8") + return source, state, samples + + +def clip(source, state, text, *args): + return subprocess.run( + [sys.executable, str(CLI), "--stage", "2", "--lang", "en", "--file", str(source), + "--output_dir", str(state), "--dest_text", text, *map(str, args)], + capture_output=True, text=True, timeout=60, + ) + + +def test_selected_audio_and_subtitle(recording): + source, state, samples = recording + result = clip(source, state, "later") + assert result.returncode == 0, result.stderr + exported, rate = sf.read(state / "result.wav", dtype="int16") + assert rate == 16000 + np.testing.assert_array_equal(exported, samples[16000:]) + assert (state / "result.srt").read_text().strip().splitlines() == [ + "1", "00:00:00,000 --> 00:00:01,000", "later"] + + +@pytest.mark.parametrize(("query", "options"), [("absent", []), ("later", ["--start_ost", 3000])]) +def test_empty_selection_produces_no_files(recording, query, options): + source, state, _ = recording + dest = state / "missing.wav" + result = clip(source, state, query, "--output_file", dest, *options) + assert result.returncode != 0, "a missing or empty selection was exported" + assert "No " in result.stderr and "Traceback" not in result.stderr + assert not dest.exists() and not dest.with_suffix(".srt").exists() + + +@pytest.mark.parametrize("suffix", [".wav", ".srt"]) +def test_existing_output_is_preserved(recording, suffix): + source, state, _ = recording + dest = state / "selected.wav" + existing = dest.with_suffix(suffix) + existing.write_bytes(b"existing recording or subtitle") + result = clip(source, state, "later", "--output_file", dest) + assert result.returncode != 0 and "already exists" in result.stderr + assert existing.read_bytes() == b"existing recording or subtitle" + assert not dest.with_suffix(".wav" if suffix == ".srt" else ".srt").exists() + + +def test_default_output_cannot_replace_input(recording): + source, state, _ = recording + source = source.rename(state / "result.wav") + before = source.read_bytes() + result = clip(source, state, "later") + assert result.returncode != 0 and "already exists" in result.stderr + assert source.read_bytes() == before + assert not (state / "result.srt").exists() + + +def test_invalid_extension_cannot_create_an_audio_file(recording): + source, state, _ = recording + dest = state / "selected.flac" + result = clip(source, state, "later", "--output_file", dest) + assert result.returncode != 0 and ".wav" in result.stderr + assert not dest.exists() and not dest.with_suffix(".srt").exists()