Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/actions/clip-export/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<a name="Community"></a>
## Community Communication🍟

Expand Down
8 changes: 8 additions & 0 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
65 changes: 40 additions & 25 deletions funclip/videoclipper.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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:
Expand All @@ -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)


Expand Down Expand Up @@ -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)
Expand Down
5 changes: 3 additions & 2 deletions scripts/verify_release_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand All @@ -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)


Expand Down
87 changes: 87 additions & 0 deletions tests/test_cli_audio_clip.py
Original file line number Diff line number Diff line change
@@ -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()