Skip to content

Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.

18.1 KB
Raw Blame
import asyncio
import itertools
import subprocess
import types
from pathlib import Path, PureWindowsPath

import numpy as np
import pytest
from mimvox_engine import media
from mimvox_engine.redub import render, subtitles, video

UK = (
    "Привіт усім, і ласкаво просимо назад на шоу. Сьогодні ми поговоримо про те, як клонують голос лише з кількох "
    "хвилин мовлення, і чому це зовсім не магія."
)
ZH = "今天我们来谈谈如何只用几分钟的语音来克隆声音。这听起来像魔术,但其实只是认真的录音和一点耐心。"


def text_of(cues):
    return " ".join(" ".join(c.lines) for c in cues)


def test_short_line_is_one_cue_at_the_placed_time():
    [cue] = subtitles.cues([(2.35, 4.1, "Hello there.")])
    assert (cue.start, cue.end, cue.lines) == (2.35, pytest.approx(4.1 + subtitles.HOLD_S), ("Hello there.",))


def test_long_text_splits_at_sentences_into_cues_of_two_lines():
    cues = subtitles.cues([(1.0, 9.0, UK)])
    assert len(cues) > 1
    assert all(1 <= len(c.lines) <= subtitles.MAX_LINES for c in cues)
    assert all(subtitles.width(ln) <= subtitles.LINE_UNITS for c in cues for ln in c.lines)
    assert cues[0].lines[-1].endswith("шоу.")
    assert text_of(cues).split() == UK.split()


def test_a_long_sentence_breaks_at_its_commas():
    text = (
        "When the storm finally passed over the hills, the villagers came out of their houses, "
        "counted the broken shutters, and started to sweep the streets before the sun went down."
    )
    cues = subtitles.cues([(0.0, 8.0, text)])
    assert len(cues) == 3
    assert [c.lines[-1][-6:] for c in cues] == ["hills,", "tters,", " down."]


def test_chinese_splits_without_spaces():
    cues = subtitles.cues([(0.0, 6.0, ZH)])
    assert "".join("".join(c.lines) for c in cues) == ZH
    assert all(len(ln) <= 17 for c in cues for ln in c.lines)
    assert cues[0].lines[-1].endswith("。")


def test_time_is_shared_by_characters_without_overlap():
    cues = subtitles.cues([(1.0, 9.0, UK), (9.0, 12.0, "Так.")])
    assert cues[0].start == 1.0
    assert cues[-2].end == pytest.approx(9.0)
    for a, b in itertools.pairwise(cues):
        assert a.end <= b.start
        assert a.end - a.start >= subtitles.MIN_S
    long = [c for c in cues if c.end <= 9.0]
    per_char = [(c.end - c.start) / len("".join(c.lines).replace(" ", "")) for c in long]
    assert max(per_char) == pytest.approx(min(per_char), rel=0.1)


def test_a_sentence_cut_into_clips_is_one_cue_again():
    lines = [
        (10.0, 13.0, "And in most cases you'd be right, as 97% of climbers use oxygen to ascend to Everest's"),
        (13.0, 15.0, "summit at 8,850 meters above sea level."),
        (15.2, 18.0, "The thin air at high altitudes makes most people breathless."),
    ]
    cues = subtitles.cues(lines)
    texts = [" ".join(c.lines) for c in cues]
    assert texts == [
        "And in most cases you'd be right,",
        "as 97% of climbers use oxygen to ascend",
        "to Everest's summit at 8,850 meters above sea level.",
        "The thin air at high altitudes makes most people breathless.",
    ]
    assert cues[2].end == pytest.approx(15.2)
    assert cues[3].start == pytest.approx(15.2)


def test_word_times_place_each_cue_where_its_words_are_spoken():
    line = (10.0, 16.0, "It is late. We should go home now.")
    words = [
        (10.0, 10.2, "It"),
        (10.2, 10.4, "is"),
        (10.4, 11.5, "late."),
        (13.0, 13.3, "We"),
        (13.3, 13.8, "should"),
        (13.8, 14.0, "go"),
        (14.0, 14.5, "home"),
        (14.5, 15.9, "now."),
    ]
    cues = subtitles.cues([line], [words])
    hold = subtitles.HOLD_S
    assert [(c.start, c.end) for c in cues] == [(10.0, pytest.approx(11.5 + hold)), (13.0, pytest.approx(15.9 + hold))]
    edited = subtitles.cues([(10.0, 16.0, "It is very late. We should go now.")], [words])
    assert edited[0].start == 10.0 and edited[1].start == pytest.approx(13.0)


def test_captions_roll_up_word_by_word():
    words = [(0.0, 0.3, "One"), (0.4, 0.8, "two"), (0.9, 1.2, "three.")]
    shown = subtitles.rollup(subtitles.cues([(0.0, 1.2, "One two three.")], [words]))
    lead = subtitles.LEAD_S
    assert [(c.start, c.lines) for c in shown] == [
        (0.0, ("One",)),
        (pytest.approx(max(0.4 - lead, subtitles.BOX_S)), ("One two",)),
        (pytest.approx(max(0.9 - lead, 2 * subtitles.BOX_S)), ("One two three.",)),
    ]
    assert shown[0].end == shown[1].start and shown[-1].end == pytest.approx(1.2 + subtitles.HOLD_S)
    long = "A caption line is filled with words until it is full and then rolls up into the line above it."
    rolled = subtitles.rollup(subtitles.cues([(0.0, 20.0, long)]))
    assert all(len(c.lines) <= 2 for c in rolled) and len(rolled[-1].lines) == 2
    assert rolled[-1].lines[0] in {c.lines[-1] for c in rolled[:-1]}


def test_a_short_pause_keeps_the_caption_and_a_long_one_clears_it():
    shown = subtitles.rollup(subtitles.cues([(0.0, 1.0, "Hello."), (2.0, 3.0, "Again."), (9.0, 10.0, "Later.")]))
    assert shown[0].end == shown[1].start == pytest.approx(2.0 - subtitles.LEAD_S)
    assert shown[1].lines == ("Hello. Again.",)
    assert shown[2].lines == ("Later.",) and shown[1].end < 9.0


def test_a_long_pause_ends_a_cue_inside_a_sentence():
    cues = subtitles.cues([(0.0, 2.0, "So the answer is"), (5.0, 6.0, "forty two.")])
    assert [" ".join(c.lines) for c in cues] == ["So the answer is", "forty two."]


def test_short_clip_stays_on_screen_into_the_gap_only():
    cues = subtitles.cues([(1.0, 1.3, "Yes."), (1.6, 3.0, "No."), (5.0, 5.2, "Maybe.")])
    assert [(c.start, c.end) for c in cues] == [(1.0, 1.6), (1.6, pytest.approx(3.3)), (5.0, pytest.approx(5.8))]


def test_overlapping_or_empty_lines_never_overlap():
    cues = subtitles.cues([(0.0, 2.0, "One two three."), (1.5, 3.0, "Four five."), (3.0, 3.0, "x"), (4.0, 5.0, "  ")])
    assert len(cues) == 2
    assert cues[0].end <= cues[1].start


def test_lines_of_chinese_without_punctuation_stay_phrases_and_roll_up_in_short_pieces():
    lines = [
        (0.0, 3.0, "他们都说谎 累训这酷的菜菜"),
        (3.0, 6.0, "搞什么投用计算 早晚被人替代"),
        (6.0, 8.0, "So AI AI Just AI AI"),
    ]
    cues = subtitles.cues(lines)
    assert [c.lines for c in cues] == [
        ("他们都说谎 累训这酷的菜菜",),
        ("搞什么投用计算 早晚被人替代",),
        ("So AI AI Just AI AI",),
    ]
    shown = subtitles.rollup(cues)
    assert all(subtitles.width(ln) <= subtitles.LINE_UNITS for c in shown for ln in c.lines)
    assert shown[0].lines == ("他们都说",) and ("他们都说谎\u3000累训这酷",) in [c.lines for c in shown]
    doc = subtitles.ass(cues, 1280, 720, "bottom", "zh")
    assert "{\\alpha&HFF&" in doc and "\u3000累训这酷" in doc


def test_ass_document():
    cues = [subtitles.Cue(0.5, 61.25, ("Hi {there}", "a\\N b")), subtitles.Cue(3661.0, 3662.0, ("x",))]
    doc = subtitles.ass(cues, 1280, 720, "top", "uk")
    head, events = doc.split("[Events]")
    assert "PlayResX: 1280\nPlayResY: 720\n" in head
    style = dict(zip(head.split("\nFormat: ")[1].split("\n")[0].split(", "), head.split("\nStyle: ")[1].split(",")))
    assert style["Fontsize"] == str(round(720 * 0.055))
    assert style["PrimaryColour"] == "&H00FFFFFF"
    lines = events.strip().splitlines()[1:]
    boxes = [ln for ln in lines if ln.startswith("Dialogue: 0,")]
    texts = [ln for ln in lines if ln.startswith("Dialogue: 1,")]
    assert len(boxes) == len(texts) and boxes
    assert all("\\p1}m " in b and " b " in b and "\\1a&H80&" in b for b in boxes)
    shows = "{\\alpha&HFF&\\t(200,201,\\alpha&H00&)}"
    assert texts[0].startswith("Dialogue: 1,0:00:00.20,0:00:00.40,Default,,0,0,0,,{\\an7\\pos(")
    assert texts[0].endswith(f"}}{shows}Hi{{\\alpha&H00&}}")
    whole = texts[3]
    assert whole.startswith("Dialogue: 1,0:00:00.80,0:01:01.25,") and "\\fad(0,600)" in whole
    assert whole.endswith(f"}}Hi \\{{there\\}} a\\\u200bN {shows}b{{\\alpha&H00&}}")
    assert all("\\clip(" in t and "\\1a" not in t for t in texts)
    assert texts[-1].startswith("Dialogue: 1,1:01:00.70,1:01:02.00,")
    top_y = int(texts[0].split("\\pos(")[1].split(",")[1].split(")")[0])
    bottom = subtitles.ass(cues, 1280, 720, "bottom").split("[Events]")[1].strip().splitlines()[2]
    assert top_y < 100 < int(bottom.split("\\pos(")[1].split(",")[1].split(")")[0])


def test_escape_flattens_newlines():
    assert subtitles.escape("one\ntwo\r\n  three") == "one two three"


def test_srt_keeps_braces_and_breaks_lines():
    doc = subtitles.srt([subtitles.Cue(0.5, 2.0, ("Hi {there}", "line two"))])
    assert doc == "1\n00:00:00,500 --> 00:00:02,000\nHi {there}\nline two\n"


def test_subtitle_files_time_each_cue_past_an_hour():
    cues = [subtitles.Cue(0.5, 2.0, ("Hi",)), subtitles.Cue(3599.9996, 3725.0424, ("Over", "an hour"))]
    assert subtitles.srt(cues).splitlines()[5] == "01:00:00,000 --> 01:02:05,042"
    assert subtitles.vtt(cues) == (
        "WEBVTT\n\n00:00:00.500 --> 00:00:02.000\nHi\n\n01:00:00.000 --> 01:02:05.042\nOver\nan hour\n"
    )
    assert subtitles.sbv(cues) == "0:00:00.500,0:00:02.000\nHi\n\n1:00:00.000,1:02:05.042\nOver\nan hour\n"
    assert subtitles.vtt([subtitles.Cue(-0.2, 100 * 3600.0, ("x",))]).splitlines()[2] == (
        "00:00:00.000 --> 100:00:00.000"
    )


def test_subtitle_files_escape_what_their_format_reads_as_markup():
    cue = subtitles.Cue(1.0, 2.0, ("a <b> & c --> d", "  tabs\tand\nbreaks "))
    assert subtitles.vtt([cue]).splitlines()[3:5] == ["a &lt;b&gt; &amp; c --&gt; d", "tabs and breaks"]
    assert subtitles.srt([subtitles.Cue(1.0, 2.0, ("C:\\N {x}",))]).splitlines()[2] == "C:\\\u200bN {x}"
    assert subtitles.sbv([cue]).splitlines()[1:3] == ["a <b> & c --> d", "tabs and breaks"]


def test_fonts_by_script_and_platform():
    assert subtitles.font_name("zh", "win32") == "Microsoft YaHei"
    assert subtitles.font_name("ja", "darwin") == "Hiragino Sans"
    assert subtitles.font_name("ko", "linux") == "Noto Sans CJK KR"
    assert subtitles.font_name("uk", "win32") == "Arial"
    assert subtitles.font_name(None, "linux") == "Noto Sans"


def test_filter_path_escapes_windows_drive_and_backslashes():
    path = PureWindowsPath(r"C:\Users\Тарас\AppData\Local\Mimvox\tmp\job1\subtitles.ass")
    assert subtitles.filter_path(path, windows=True) == r"C\\:/Users/Тарас/AppData/Local/Mimvox/tmp/job1/subtitles.ass"


def test_filter_path_escapes_graph_characters():
    assert subtitles.filter_path("/tmp/it's [a], b;c:d.ass", windows=False) == r"/tmp/it\\\'s \[a\]\, b\;c\\:d.ass"


@pytest.fixture
def fake_ffmpeg(monkeypatch, tmp_path):
    calls = []

    def run(cmd, timeout=3600.0, data=None):
        calls.append([str(c) for c in cmd])
        if str(cmd[0]).endswith("ffprobe"):
            return subprocess.CompletedProcess(cmd, 0, b"", b"")
        part = Path(cmd[-1])
        fail = run.fail(calls[-1])
        if not fail:
            part.write_bytes(b"video")
        return subprocess.CompletedProcess(cmd, 1 if fail else 0, b"", b"refused" if fail else b"")

    run.fail = lambda cmd: False
    monkeypatch.setattr(media, "_run", run)
    monkeypatch.setattr(media, "require_ffmpeg", lambda: Path("ffmpeg"))
    monkeypatch.setattr(media, "ffprobe_path", lambda: Path("ffprobe"))
    monkeypatch.setattr(media, "_ffmpeg_lists", lambda: (set(), set(), {"aac", "libopus", "libx264", "mov_text"}, "8"))
    monkeypatch.setattr(media, "_ffmpeg_filters", lambda: {"subtitles", "atempo"})
    monkeypatch.setattr(video, "picture_size", lambda path: (1280, 720))
    monkeypatch.setattr(media, "h264_hardware", lambda: None)
    return types.SimpleNamespace(calls=calls, run=run, dir=tmp_path)


def muxes(f):
    return [c for c in f.calls if c[0] == "ffmpeg"]


def inputs(cmd):
    return [cmd[i + 1] for i, a in enumerate(cmd) if a == "-i"]


def test_mux_without_subtitles_copies_the_picture(fake_ffmpeg):
    f = fake_ffmpeg
    info = video.mux(f.dir / "in.mp4", f.dir / "mix.wav", f.dir / "out.mp4", "mp4", "ukr")
    [cmd] = muxes(f)
    assert info == {"audio_codec": "aac", "faststart": True, "video_codec": "copy", "subtitles": {}}
    assert cmd[cmd.index("-c") + 1] == "copy"
    assert "-filter_complex" not in cmd
    assert "-c:v" not in cmd
    assert cmd[cmd.index("0:v") - 1] == "-map"
    assert "-hwaccel" not in cmd
    assert (f.dir / "out.mp4").read_bytes() == b"video"


def test_mux_burns_subtitles_with_x264(fake_ffmpeg):
    f = fake_ffmpeg
    plan = subtitles.Plan([(0.5, 2.0, "Привіт {усім}.")], "uk", "bottom", f.dir / "s.ass")
    info = video.mux(f.dir / "in.mp4", f.dir / "mix.wav", f.dir / "out.mp4", "mp4", "ukr", plan)
    [cmd] = muxes(f)
    assert len(inputs(cmd)) == 2
    graph = cmd[cmd.index("-filter_complex") + 1]
    assert graph.startswith("[0:V:0]subtitles=filename=") and graph.endswith("s.ass[v]")
    assert cmd[cmd.index("-c:v") + 1 : cmd.index("-c:v") + 5] == ["libx264", "-crf", "18", "-preset"]
    assert "mov_text" not in cmd  # MP4 shows its only subtitle track: it would draw the text twice
    assert info["video_codec"] == "libx264"
    assert info["subtitles"] == {"subtitles_burned": True, "subtitle_lines": 1}
    assert "PlayResY: 720" in (f.dir / "s.ass").read_text(encoding="utf-8")


def test_mux_burns_with_the_hardware_encoder_first(fake_ffmpeg, monkeypatch):
    f = fake_ffmpeg
    monkeypatch.setattr(media, "h264_hardware", lambda: "h264_vaapi")
    plan = subtitles.Plan([(0.5, 2.0, "Hello.")], "en", "bottom", f.dir / "s.ass")
    info = video.mux(f.dir / "in.mp4", f.dir / "mix.wav", f.dir / "out.mp4", "mp4", "eng", plan)
    [cmd] = muxes(f)
    assert cmd[cmd.index("-hwaccel") + 1] == "auto"
    assert cmd.index("-hwaccel") < cmd.index("-i")
    assert cmd[cmd.index("-filter_complex") + 1].endswith("s.ass,format=nv12,hwupload[v]")
    assert cmd[cmd.index("-c:v") + 1] == "h264_vaapi"
    assert cmd[cmd.index("-vaapi_device") + 1] == media.VAAPI_DEVICE
    assert info["video_codec"] == "h264_vaapi"


def test_mux_burns_and_adds_a_track_to_mkv(fake_ffmpeg, monkeypatch):
    f = fake_ffmpeg
    monkeypatch.setattr(media, "_ffmpeg_lists", lambda: (set(), set(), {"libopus", "libx264", "ass"}, "8"))
    plan = subtitles.Plan([(0.5, 2.0, "Hello.")], "en", "top", f.dir / "s.ass")
    info = video.mux(f.dir / "in.mkv", f.dir / "mix.wav", f.dir / "out.mkv", "mkv", "eng", plan)
    [cmd] = muxes(f)
    assert inputs(cmd)[2].endswith("s.ass")
    k = cmd.index("2:0")
    assert cmd[k + 1 : k + 7] == ["-c:s:0", "ass", "-disposition:s:0", "0", "-metadata:s:s:0", "language=eng"]
    assert info["subtitles"]["subtitles_burned"] is True


def test_mux_without_libass_adds_a_shown_track_and_a_note(fake_ffmpeg, monkeypatch):
    f = fake_ffmpeg
    monkeypatch.setattr(media, "_ffmpeg_filters", lambda: {"atempo"})
    plan = subtitles.Plan([(0.5, 2.0, "Hello."), (3.0, 4.0, "Bye.")], "en", "bottom", f.dir / "s.ass")
    info = video.mux(f.dir / "in.mp4", f.dir / "mix.wav", f.dir / "out.mp4", "mp4", "eng", plan)
    [cmd] = muxes(f)
    assert "-filter_complex" not in cmd
    assert cmd[cmd.index("-c") + 1] == "copy"
    assert cmd[cmd.index("-c:s:0") + 1] == "mov_text"
    assert cmd[cmd.index("-disposition:s:0") + 1] == "default"
    assert inputs(cmd)[2].endswith("s.srt")
    assert info["subtitles"]["subtitles_burned"] is False
    assert info["subtitles"]["subtitle_lines"] == 2
    assert "libass" in info["subtitles"]["subtitle_note"]


def test_mux_falls_back_to_the_copied_picture_when_burning_fails(fake_ffmpeg):
    f = fake_ffmpeg
    f.run.fail = lambda cmd: "-filter_complex" in cmd
    plan = subtitles.Plan([(0.5, 2.0, "Hello.")], "en", "bottom", f.dir / "s.ass")
    info = video.mux(f.dir / "in.mp4", f.dir / "mix.wav", f.dir / "out.mp4", "mp4", "eng", plan)
    last = muxes(f)[-1]
    assert "-filter_complex" not in last
    assert "mov_text" in last
    assert info["video_codec"] == "copy"
    assert info["subtitles"]["subtitles_burned"] is False
    assert "could not be drawn" in info["subtitles"]["subtitle_note"]


def test_mux_with_nothing_spoken_writes_no_subtitles(fake_ffmpeg):
    f = fake_ffmpeg
    plan = subtitles.Plan(None, None, "bottom", f.dir / "s.ass")
    info = video.mux(f.dir / "in.mp4", f.dir / "mix.wav", f.dir / "out.mp4", "mp4", None, plan)
    [cmd] = muxes(f)
    assert "-filter_complex" not in cmd
    assert info["subtitles"]["subtitle_lines"] == 0
    assert "Convert voice" in info["subtitles"]["subtitle_note"]


def test_options_take_subtitles_only_for_a_video(monkeypatch, tmp_path):
    monkeypatch.setattr(media, "probe", lambda path: {"has_video": True})
    src = tmp_path / "a.mp4"
    out = video.options({"output": "video", "subtitles": True, "subtitle_position": "top"}, src)
    assert (out.subtitles, out.subtitle_position) == (True, "top")
    assert not video.options({"output": "audio", "subtitles": True}, src).subtitles
    assert video.options({"output": "video"}, src).subtitle_position == "bottom"
    with pytest.raises(Exception, match="subtitle_position"):
        video.options({"output": "video", "subtitles": True, "subtitle_position": "middle"}, src)


class _Backend:
    def __init__(self, seconds):
        self.seconds = seconds

    async def synthesize(self, text, lang, ref, params):
        return Path(params.out_path)


def test_respeak_reports_where_each_clip_lands(monkeypatch, tmp_path):
    lengths = iter([2.0, 0.5])
    monkeypatch.setattr(
        render, "_load_trimmed", lambda path: (np.full(int(next(lengths) * render.SR), 0.1, np.float32), render.SR)
    )
    monkeypatch.setattr(media, "time_stretch", lambda y, sr, rate: None)
    segs = [{"start": 0.5, "end": 1.0, "text": "First one."}, {"start": 1.2, "end": 2.0, "text": "Second."}]
    _, stats = asyncio.run(
        render.respeak(
            segs,
            3.0,
            "ref.wav",
            0.8,
            "best",
            None,
            "",
            "",
            0.0,
            tmp_path,
            lambda *a, **k: None,
            backend=_Backend(1.0),
        )
    )
    (a0, b0, t0), (a1, b1, t1) = stats["lines"]
    assert (a0, t0, t1) == (0.5, "First one.", "Second.")
    assert b0 == pytest.approx(2.5, abs=1e-3)
    assert a1 == pytest.approx(2.5 + render.CLIP_GAP_S)
    assert b1 - a1 == pytest.approx(0.5, abs=1e-3)
    assert stats["pushed"] == 1