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: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ python funclip/videoclipper.py --stage 2 \
--output_file './output/res.mp4'
```

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.

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

Expand Down
2 changes: 2 additions & 0 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,8 @@ python funclip/videoclipper.py --stage 2 \
--output_file './output/res.mp4'
```

这条**第二阶段视频剪辑**命令退出码为 0 时,应同时得到 `./output/res.mp4` 和 `./output/res.srt`。使用 `--output_file` 时请选择新文件名:已有的视频或同名字幕均不会被覆盖。未匹配到文字时,命令以非零状态退出,不生成这两个文件;请先从已保存的转写结果核对选词,再重试。

### C.通过创空间与Space体验FunClip

[FunClip@Modelscope创空间⭐](https://modelscope.cn/studios/iic/funasr_app_clipvideo/summary)
Expand Down
58 changes: 45 additions & 13 deletions funclip/videoclipper.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@
import re
import os
import sys
import tempfile
from contextlib import ExitStack
from pathlib import Path
import copy
import librosa
import logging
Expand Down Expand Up @@ -475,6 +478,47 @@ def get_parser():
return parser


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:
video = source.with_name(source.stem + "_clip_no0.mp4")
subtitle = source.with_name(source.stem + "_clip.srt")
else:
video = Path(output_file)
if video.suffix.lower() != ".mp4":
raise SystemExit("Video --output_file must end with .mp4")
subtitle = video.with_suffix(".srt")
for path in (video, subtitle):
if os.path.lexists(path):
raise SystemExit(f"Output already exists: {path}")

# The shared UI clipper numbers each render. Keep those names private to
# the CLI call and publish only the selected video and its subtitle.
with tempfile.TemporaryDirectory(dir=video.parent) as tmp:
with mpy.VideoFileClip(file) as media:
state.update(video=media, video_filename=file, clip_video_file=os.path.join(tmp, "clip.mp4"))
rendered, message, srt = clipper.video_clip(dest_text, start_ost, end_ost, state, dest_spk=dest_spk)
if rendered is None:
raise SystemExit(message)
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()
logging.warning("Saved clipped video to %s and subtitles to %s", video, subtitle)


def runner(stage, file, sd_switch, output_dir, dest_text, dest_spk, start_ost, end_ost, output_file, config=None, lang='zh'):
audio_suffixs = ['.wav','.mp3','.aac','.m4a','.flac']
video_suffixs = ['.mp4','.avi','.mkv','.flv','.mov','.webm','.ts','.mpeg']
Expand Down Expand Up @@ -544,19 +588,7 @@ def runner(stage, file, sd_switch, output_dir, dest_text, dest_spk, start_ost, e
logging.warning("Write clipped subtitle to {}".format(clip_srt_file))
if mode == 'video':
state = load_state(output_dir)
state['video_filename'] = file
if output_file is None:
state['clip_video_file'] = file[:-4] + '_clip.mp4'
else:
state['clip_video_file'] = output_file
clip_srt_file = state['clip_video_file'][:-3] + 'srt'
state['video'] = mpy.VideoFileClip(file)
clip_video_file, message, srt_clip = audio_clipper.video_clip(dest_text, start_ost, end_ost, state, dest_spk=dest_spk)
logging.warning("Clipping Log: {}".format(message))
logging.warning("Save clipped mp4 file to {}".format(clip_video_file))
with open(clip_srt_file, 'w') as fout:
fout.write(srt_clip)
logging.warning("Write clipped subtitle to {}".format(clip_srt_file))
_export_cli_video(audio_clipper, file, state, output_file, dest_text, dest_spk, start_ost, end_ost)


def main(cmd=None):
Expand Down
109 changes: 72 additions & 37 deletions tests/test_cli_video_clip.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,41 +12,76 @@


class CLIClipTests(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory()
self.addCleanup(tmp.cleanup)
self.root = Path(tmp.name)
self.source = self.root / "input.mp4"
parts = [ColorClip((64, 48), color=c, duration=1) for c in [(230, 20, 20), (20, 20, 230)]]
with concatenate_videoclips(parts) as video:
video.write_videofile(str(self.source), fps=10, audio=False, logger=None)

def clip(self, state, words, query, *opts):
state.mkdir(exist_ok=True)
spans = [[0, 1000], [1000, 2000]]
for name, value in {
"recog_res_raw": " ".join(words),
"timestamp": repr(spans),
"sentences": repr([{"text": w, "timestamp": [t]} for w, t in zip(words, spans)]),
}.items():
(state / name).write_text(value, encoding="utf-8")
return subprocess.run(
[sys.executable, str(CLI), "--stage", "2", "--file", str(self.source),
"--output_dir", str(state), "--dest_text", query, *map(str, opts)],
env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"},
capture_output=True, text=True, encoding="utf-8", timeout=60,
)

def assert_export(self, path, subtitle, word):
with VideoFileClip(str(path)) as result:
self.assertAlmostEqual(result.duration, 1.0, delta=0.1)
red, _, blue = result.get_frame(0.5).mean(axis=(0, 1))
self.assertGreater(blue - red, 150, "expected the blue second half")
text = subtitle.read_text(encoding="utf-8")
self.assertIn("00:00:00,000 --> 00:00:01,000", text)
self.assertEqual(text.strip().splitlines()[-1].strip(), word)

def test_stage_two_exports_the_selected_video_and_subtitle(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
source = root / "input.mp4"
parts = [ColorClip((64, 48), color=c, duration=1) for c in [(230, 20, 20), (20, 20, 230)]]
with concatenate_videoclips(parts) as video:
video.write_videofile(str(source), fps=10, audio=False, logger=None)
for lang, words, opts in [
("zh", ["早", "晚"], []),
("en", ["early", "later"], ["--lang", "en"]),
]:
with self.subTest(lang=lang):
state = root / lang
state.mkdir()
spans = [[0, 1000], [1000, 2000]]
for name, value in {
"recog_res_raw": " ".join(words),
"timestamp": repr(spans),
"sentences": repr([{"text": w, "timestamp": [t]} for w, t in zip(words, spans)]),
}.items():
(state / name).write_text(value, encoding="utf-8")
proc = subprocess.run(
[sys.executable, str(CLI), "--stage", "2", "--file", str(source),
"--output_dir", str(state), "--output_file", str(state / "result.mp4"),
"--dest_text", words[1], *opts],
env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"},
capture_output=True, text=True, encoding="utf-8", timeout=60,
)
self.assertEqual(proc.returncode, 0, proc.stderr)
clips = list(state.glob("*.mp4"))
self.assertEqual(len(clips), 1, clips)
with VideoFileClip(str(clips[0])) as result:
self.assertAlmostEqual(result.duration, 1.0, delta=0.1)
red, _, blue = result.get_frame(0.5).mean(axis=(0, 1))
self.assertGreater(blue - red, 150, "expected the blue second half")
srt = (state / "result.srt").read_text(encoding="utf-8")
self.assertIn("00:00:00,000 --> 00:00:01,000", srt)
self.assertEqual(srt.strip().splitlines()[-1].strip(), words[1])
for lang, words, opts in [
("zh", ["早", "晚"], []),
("en", ["early", "later"], ["--lang", "en"]),
]:
with self.subTest(lang=lang):
dest = self.root / lang
dest.mkdir()
video = dest / "selected clip.v2.mp4"
proc = self.clip(self.root / "state", words, words[1], "--output_file", video, *opts)
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertEqual(set(dest.iterdir()), {video, video.with_suffix(".srt")})
self.assert_export(video, video.with_suffix(".srt"), words[1])

def test_no_match_fails_without_creating_a_subtitle_or_video(self):
dest = self.root / "export"
dest.mkdir()
proc = self.clip(self.root / "state", ["早", "晚"], "雪", "--output_file", dest / "missing.mp4")
self.assertNotEqual(proc.returncode, 0)
self.assertIn("No period found", proc.stderr)
self.assertEqual(list(dest.iterdir()), [])

def test_existing_explicit_artifacts_are_not_replaced(self):
for suffix in [".mp4", ".srt"]:
with self.subTest(suffix=suffix):
dest = self.root / suffix[1:]
dest.mkdir()
video = dest / "chosen.mp4"
existing = video.with_suffix(suffix)
existing.write_bytes(b"existing user output")
proc = self.clip(self.root / "state", ["早", "晚"], "晚", "--output_file", video)
self.assertNotEqual(proc.returncode, 0)
self.assertEqual(existing.read_bytes(), b"existing user output")
self.assertEqual(list(dest.iterdir()), [existing])

def test_default_paths_still_work_without_output_file(self):
proc = self.clip(self.root / "state", ["早", "晚"], "晚")
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assert_export(self.root / "input_clip_no0.mp4", self.root / "input_clip.srt", "晚")