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.

11.3 KB
Raw Blame
import asyncio
import json
import re
import subprocess

import numpy as np
import pytest
import soundfile as sf
from mimvox_engine import media, results, tts, videoexport
from mimvox_engine.redub import handlers
from mimvox_engine.registry import EngineError

SR = 16000
LINES = [{"start": 0.1, "end": 0.7, "text": "Hello there."}, {"start": 0.8, "end": 1.1, "text": "Second line."}]


class Ctx:
    def __init__(self, tmp_path):
        self.data_dir = str(tmp_path / "data")
        self.runtime = {}
        self.events = []
        self.jobs = {}

    def emit(self, event, data, job=None):
        self.events.append((event, data))

    def start_job(self, fn):
        job = f"job-{len(self.jobs) + 1}"
        self.jobs[job] = fn
        return job


def render(ctx, **params):
    return asyncio.run(handlers.redub_render(ctx, {"mode": "subtitles", **params}))


def run(ctx, **params):
    job = render(ctx, **params)["job"]
    asyncio.run(ctx.jobs[job](job))
    return ctx.events[-1]


@pytest.fixture
def sound(tmp_path):
    path = tmp_path / "talk.wav"
    t = np.arange(int(2.5 * SR)) / SR
    sf.write(path, (0.3 * np.sin(2 * np.pi * 220 * t)).astype(np.float32), SR)
    return path


@pytest.mark.parametrize(
    ("params", "message"),
    [
        ({}, "subtitles needs 'segments'"),
        ({"segments": []}, "subtitles needs 'segments'"),
        ({"segments": [{"start": 0, "end": 1, "text": "  "}]}, "all segments are empty"),
        ({"segments": [{"start": 1, "end": 0.5, "text": "Back."}]}, "start <= end"),
        ({"segments": LINES, "subtitle_position": "middle"}, "'subtitle_position'"),
        ({"segments": LINES, "language": "not a code"}, "'language'"),
        ({"segments": LINES, "output_format": "doc"}, "'output_format'"),
    ],
)
def test_bad_requests(tmp_path, sound, params, message):
    with pytest.raises(EngineError, match=message) as err:
        render(Ctx(tmp_path), path=str(sound), **params)
    assert err.value.code == "bad_request"


@pytest.fixture
def photos(tmp_path):
    for name in ("a.png", "b.png"):
        (tmp_path / name).write_bytes(b"png")
    return tmp_path


@pytest.mark.parametrize(
    ("images", "code", "message"),
    [
        ("a.png", "bad_request", "'images' must be a list"),
        (["a.png"], "bad_request", "image 1 needs a 'path'"),
        ([{"start": 0}], "bad_request", "image 1 needs a 'path'"),
        ([{"path": ""}], "bad_request", "image 1 needs a 'path'"),
        ([{"path": "a.png", "start": 0}, {"path": "b.png", "start": True}], "bad_request", "the start of image 2"),
        ([{"path": "a.png", "start": 0}, {"path": "b.png", "start": -1}], "bad_request", "the start of image 2"),
        ([{"path": "a.png", "start": 0}, {"path": "b.png"}], "bad_request", "give every image a start, or none"),
        ([{"path": "a.png", "start": 1}, {"path": "b.png", "start": 2}], "bad_request", "the first image must start"),
        ([{"path": "a.png", "start": 0}, {"path": "b.png", "start": 0}], "bad_request", "image 2 must start after"),
        ([{"path": "a.png"}, {"path": "gone.png"}], "not_found", "image not found"),
    ],
)
def test_bad_images(tmp_path, sound, photos, images, code, message):
    if isinstance(images, list):
        images = [
            {**i, "path": str(photos / i["path"])} if isinstance(i, dict) and i.get("path") else i for i in images
        ]
    with pytest.raises(EngineError, match=re.escape(message)) as err:
        render(Ctx(tmp_path), path=str(sound), segments=LINES, images=images)
    assert err.value.code == code


def test_unknown_mode_names_the_modes(tmp_path, sound):
    with pytest.raises(EngineError, match='"subtitles"'):
        asyncio.run(handlers.redub_render(Ctx(tmp_path), {"path": str(sound), "mode": "sing"}))


def ffmpeg_can(*encoders):
    if media.ffmpeg_path() is None or media.ffprobe_path() is None:
        return False
    return set(encoders) <= media._ffmpeg_lists()[2]


needs_x264 = pytest.mark.skipif(not ffmpeg_can("libx264", "aac"), reason="needs ffmpeg with libx264 and aac")
burns = "subtitles" in media._ffmpeg_filters() if media.ffmpeg_path() else False


def ff(*args):
    subprocess.run([str(media.ffmpeg_path()), "-v", "error", "-y", *map(str, args)], check=True)


def gray_frame(path, at):
    """The frame at ``at`` seconds as 8-bit luma."""
    cmd = [str(media.ffmpeg_path()), "-v", "error", "-ss", str(at), "-i", str(path), "-frames:v", "1"]
    out = subprocess.run([*cmd, "-f", "rawvideo", "-pix_fmt", "gray", "pipe:1"], check=True, capture_output=True)
    return np.frombuffer(out.stdout, np.uint8)


def picture(path):
    exe = str(media.ffprobe_path())
    cmd = [exe, "-v", "error", "-show_entries", "stream=codec_type,codec_name,width,height", "-of", "json", str(path)]
    streams = json.loads(subprocess.run(cmd, check=True, capture_output=True).stdout)["streams"]
    return {s["codec_type"]: s for s in streams}


def check_saved(tmp_path, data, video_ext):
    outputs = tmp_path / "data" / "outputs"
    video = data["video_path"]
    assert video.parent == outputs and video.suffix == video_ext and video.stem == data["path"].stem
    side = json.loads(results.sidecar_path(data["path"]).read_text(encoding="utf-8"))
    assert {k: side[k] for k in ("kind", "mode", "language", "video_path")} == {
        "kind": "redub",
        "mode": "subtitles",
        "language": "en",
        "video_path": str(video),
    }
    assert side["segments"] == LINES
    (entry,) = results.list_results(handlers.config.data_dir(Ctx(tmp_path)))["results"]
    assert entry["mode"] == "subtitles" and entry["video_path"] == video
    assert not (tmp_path / "data" / "tmp" / "job-1").exists()
    assert not list(outputs.glob("*.part*"))


@needs_x264
def test_a_sound_file_gets_a_black_mp4_with_its_sound(tmp_path, sound):
    ctx = Ctx(tmp_path)
    event, data = run(ctx, path=str(sound), segments=LINES, language="en", output_format="wav", voice_id="nobody")
    assert event == "redub.done", data
    assert data["mode"] == "subtitles" and data["output"] == "video"
    assert data["subtitles_burned"] is burns
    assert data["subtitle_lines"] == (2 if burns else 0)
    assert ("subtitle_note" in data) is not burns
    assert [s["text"] for s in data["segments"]] == ["Hello there.", "Second line."]
    assert data["duration_s"] == pytest.approx(2.5, abs=0.01)
    saved, rate = sf.read(data["path"])
    assert (rate, len(saved)) == (44100, 2.5 * 44100)
    check_saved(tmp_path, data, ".mp4")
    streams = picture(data["video_path"])
    assert (streams["video"]["width"], streams["video"]["height"]) == (1920, 1080)
    assert streams["audio"]["codec_name"] == "aac"
    assert media.probe(data["video_path"])["duration_s"] == pytest.approx(2.5, abs=0.1)
    assert gray_frame(data["video_path"], 2.2).max() < 30
    if burns:
        assert gray_frame(data["video_path"], 0.4).max() > 200
    stages = [d["stage"] for e, d in ctx.events if e == "redub.progress"]
    assert stages[0] == "subtitles" and "encode" in stages and stages[-1] == "save"
    pcts = [d["pct"] for e, d in ctx.events if e == "redub.progress"]
    assert pcts == sorted(pcts) and pcts[-1] == 100
    assert tts._ACTIVE[0] is None


@needs_x264
def test_photos_follow_their_starts_over_a_sound_file(tmp_path, sound):
    dark, light = tmp_path / "dark.png", tmp_path / "light.png"
    ff("-f", "lavfi", "-i", "color=c=0x202020:s=320x180", "-frames:v", "1", dark)
    ff("-f", "lavfi", "-i", "color=c=white:s=180x320", "-frames:v", "1", light)
    late = [{"path": str(dark), "start": 0}, {"path": str(light), "start": 2.5}]
    with pytest.raises(EngineError, match=r"image 2 starts at 2\.5 s, after the end") as err:
        render(Ctx(tmp_path), path=str(sound), segments=LINES, images=late)
    assert err.value.code == "bad_request"
    images = [{"path": str(dark), "start": 0}, {"path": str(light), "start": 1.6}]
    event, data = run(Ctx(tmp_path), path=str(sound), segments=LINES, language="en", images=images)
    assert event == "redub.done", data
    assert ("subtitle_note" in data) is not burns
    streams = picture(data["video_path"])
    assert (streams["video"]["width"], streams["video"]["height"]) == (1920, 1080)
    for at in (0.05, 1.3, 1.5):
        assert np.median(gray_frame(data["video_path"], at)) < 60, at
    for at in (1.7, 2.3):
        assert gray_frame(data["video_path"], at).min() > 200, at


@needs_x264
def test_a_video_keeps_its_picture_and_sound_with_the_words_burned_in_unless_photos_replace_it(tmp_path):
    path = tmp_path / "clip.mp4"
    black = ["-f", "lavfi", "-i", "color=c=black:s=160x90:r=25:d=1.2", "-f", "lavfi", "-i", "sine=d=1.2"]
    ff(*black, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", path)
    photo = tmp_path / "photo.png"
    ff("-f", "lavfi", "-i", "color=c=white:s=64x48", "-frames:v", "1", photo)
    args = {"segments": LINES, "language": "en", "subtitle_position": "top"}
    event, data = run(Ctx(tmp_path), path=str(path), **args)
    assert event == "redub.done", data
    assert data["subtitles_burned"] is burns
    check_saved(tmp_path, data, ".mp4")
    streams = picture(data["video_path"])
    assert (streams["video"]["codec_name"], streams["audio"]["codec_name"]) == ("h264", "aac")
    assert (streams["video"]["width"], streams["video"]["height"]) == (160, 90)
    assert media.probe(data["video_path"])["duration_s"] == pytest.approx(1.2, abs=0.1)
    if burns:
        frame = gray_frame(data["video_path"], 0.4).reshape(90, 160)
        assert frame[:45].max() > 200
        assert frame[60:].max() < 30
    event, data = run(Ctx(tmp_path), path=str(path), **args, images=[{"path": str(photo)}])
    assert event == "redub.done", data
    assert np.median(gray_frame(data["video_path"], 0.4)) > 200
    event, data = run(Ctx(tmp_path), path=str(path), **args, picture="black")
    assert event == "redub.done", data
    assert np.median(gray_frame(data["video_path"], 0.4)) < 30
    with pytest.raises(EngineError, match="'picture'"):
        render(Ctx(tmp_path), path=str(path), segments=LINES, picture="blue")
    assert media.probe(data["video_path"])["duration_s"] == pytest.approx(1.2, abs=0.1)


@needs_x264
def test_the_cues_of_a_video_follow_its_late_sound(tmp_path):
    path = tmp_path / "late.mp4"
    picture_in = ["-f", "lavfi", "-i", "color=c=black:s=64x48:r=25:d=2"]
    ff(*picture_in, "-itsoffset", "0.5", "-f", "lavfi", "-i", "sine=d=1.5", "-c:v", "libx264", "-c:a", "aac", path)
    assert videoexport.audio_offset(path) == pytest.approx(0.5, abs=0.05)
    assert videoexport.audio_offset(tmp_path / "missing.mp4") == 0.0


@needs_x264
def test_a_cancelled_job_leaves_no_result(tmp_path, sound, monkeypatch):
    async def stopped(*_args):
        raise asyncio.CancelledError

    monkeypatch.setattr(videoexport, "make", stopped)
    event, data = run(Ctx(tmp_path), path=str(sound), segments=LINES)
    assert (event, data["code"]) == ("redub.error", "cancelled")
    assert not list((tmp_path / "data").glob("outputs/*"))
    assert not (tmp_path / "data" / "tmp" / "job-1").exists()
    assert tts._ACTIVE[0] is None


@needs_x264
def test_a_file_without_sound_is_refused(tmp_path):
    path = tmp_path / "silent.mp4"
    ff("-f", "lavfi", "-i", "color=c=black:s=64x48:r=25:d=1", "-c:v", "libx264", "-pix_fmt", "yuv420p", path)
    with pytest.raises(EngineError, match="no usable audio") as err:
        render(Ctx(tmp_path), path=str(path), segments=LINES)
    assert err.value.code == "bad_request"