mirror of
https://github.com/fscotto/infra.git
synced 2026-11-26 05:39:52 +00:00
Add offline ai-media presets for video and audio workflows
This commit is contained in:
384
ansible/roles/desktop_ai_media/files/preset.py
Normal file
384
ansible/roles/desktop_ai_media/files/preset.py
Normal file
@@ -0,0 +1,384 @@
|
|||||||
|
"""Small host-side orchestrator for offline ai-media presets."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
from datetime import datetime
|
||||||
|
import ipaddress
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
|
||||||
|
NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]*\Z")
|
||||||
|
SOURCE_NAMES = tuple(f"source{number}.jpg" for number in range(11, 19))
|
||||||
|
|
||||||
|
|
||||||
|
def video_url(value):
|
||||||
|
parsed = urlsplit(value)
|
||||||
|
if parsed.scheme not in ("http", "https") or not parsed.hostname or parsed.username or parsed.password:
|
||||||
|
raise ValueError("Use an HTTP(S) video URL without embedded credentials")
|
||||||
|
host = parsed.hostname.lower().rstrip(".")
|
||||||
|
if host == "localhost" or host.endswith(".localhost"):
|
||||||
|
raise ValueError("Local URLs are not accepted")
|
||||||
|
try:
|
||||||
|
address = ipaddress.ip_address(host)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
if not address.is_global:
|
||||||
|
raise ValueError("Private or local IP URLs are not accepted")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def media_file(root, name, *, video=False):
|
||||||
|
if not NAME.fullmatch(name) or name in (".", ".."):
|
||||||
|
raise ValueError("Use a simple filename in the ai-media input directory")
|
||||||
|
path = root / "input" / name
|
||||||
|
if not path.is_file() or path.is_symlink():
|
||||||
|
raise FileNotFoundError(path)
|
||||||
|
if video and path.suffix.lower() != ".mp4":
|
||||||
|
raise ValueError("The video must be an MP4 file")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def audio_file(root, name):
|
||||||
|
if not name or any(not NAME.fullmatch(part) or part in (".", "..")
|
||||||
|
for part in name.split("/")):
|
||||||
|
raise ValueError("Use an audio path relative to input/ or output/ without traversal")
|
||||||
|
matches = [root / directory / name for directory in ("input", "output")]
|
||||||
|
matches = [path for path in matches if path.is_file() and path.resolve() == path]
|
||||||
|
if len(matches) != 1:
|
||||||
|
raise ValueError("Audio must exist in exactly one of input/ or output/")
|
||||||
|
return matches[0]
|
||||||
|
|
||||||
|
|
||||||
|
def container_path(root, path):
|
||||||
|
directory = path.relative_to(root).parts[0]
|
||||||
|
if directory not in ("input", "output"):
|
||||||
|
raise ValueError("Media path outside input/output")
|
||||||
|
return "/work/" + str(path.relative_to(root))
|
||||||
|
|
||||||
|
|
||||||
|
def run(*command):
|
||||||
|
print("+", " ".join(map(str, command)), flush=True)
|
||||||
|
subprocess.run([str(part) for part in command], check=True)
|
||||||
|
|
||||||
|
|
||||||
|
def has_stream(path, kind):
|
||||||
|
result = subprocess.run([
|
||||||
|
"ffprobe", "-v", "error", "-show_entries", "stream=codec_type",
|
||||||
|
"-of", "json", str(path),
|
||||||
|
], check=True, capture_output=True, text=True)
|
||||||
|
return kind in [stream["codec_type"] for stream in json.loads(result.stdout)["streams"]]
|
||||||
|
|
||||||
|
|
||||||
|
def probe(path, kind):
|
||||||
|
if not has_stream(path, kind):
|
||||||
|
raise RuntimeError(f"Missing {kind} stream: {path}")
|
||||||
|
|
||||||
|
|
||||||
|
def duration(path):
|
||||||
|
result = subprocess.run([
|
||||||
|
"ffprobe", "-v", "error", "-show_entries", "format=duration",
|
||||||
|
"-of", "default=noprint_wrappers=1:nokey=1", str(path),
|
||||||
|
], check=True, capture_output=True, text=True)
|
||||||
|
return float(result.stdout.strip())
|
||||||
|
|
||||||
|
|
||||||
|
def output_path(root, video, suffix, extension="mp4"):
|
||||||
|
return root / "output" / f"{video.stem}-{suffix}.{extension}"
|
||||||
|
|
||||||
|
|
||||||
|
def mix_target(root, args):
|
||||||
|
name = args.output or f"{Path(args.vocals).stem}-mix.wav"
|
||||||
|
return wav_target(root, name)
|
||||||
|
|
||||||
|
|
||||||
|
def wav_target(root, name):
|
||||||
|
if not NAME.fullmatch(name) or Path(name).suffix.lower() != ".wav":
|
||||||
|
raise ValueError("Use a simple WAV output filename")
|
||||||
|
target = root / "output" / name
|
||||||
|
if target.exists() or target.is_symlink():
|
||||||
|
raise FileExistsError(target)
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def process_voice(args, root, launcher):
|
||||||
|
source = audio_file(root, args.audio)
|
||||||
|
probe(source, "audio")
|
||||||
|
target = wav_target(root, args.output or f"{source.stem}-mia_voce.wav")
|
||||||
|
job = root / "output" / f".{source.stem}-voice-convert-{args.job_id}"
|
||||||
|
job.mkdir(mode=0o700)
|
||||||
|
print("Working directory:", job, flush=True)
|
||||||
|
prepared = job / "audio.wav"
|
||||||
|
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||||
|
"-i", container_path(root, source), "-map", "0:a:0", "-vn",
|
||||||
|
"-c:a", "pcm_s16le", container_path(root, prepared))
|
||||||
|
run(launcher, "rvc", "cli", container_path(root, prepared),
|
||||||
|
container_path(root, job), "--convert-only")
|
||||||
|
converted = job / "vocals-mia_voce.wav"
|
||||||
|
probe(converted, "audio")
|
||||||
|
os.link(converted, target)
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def process_mix(args, root, launcher):
|
||||||
|
vocals = audio_file(root, args.vocals)
|
||||||
|
instrumental = audio_file(root, args.instrumental)
|
||||||
|
target = mix_target(root, args)
|
||||||
|
for source in (vocals, instrumental):
|
||||||
|
probe(source, "audio")
|
||||||
|
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||||
|
"-i", container_path(root, vocals), "-i", container_path(root, instrumental),
|
||||||
|
"-filter_complex", "[0:a][1:a]amix=inputs=2:duration=longest:normalize=0[a]",
|
||||||
|
"-map", "[a]", "-c:a", "pcm_s16le", container_path(root, target))
|
||||||
|
probe(target, "audio")
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def mux(launcher, root, video, audio, target):
|
||||||
|
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||||
|
"-i", container_path(root, video), "-i", container_path(root, audio),
|
||||||
|
"-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac",
|
||||||
|
"-b:a", "192k", "-shortest", "-movflags", "+faststart",
|
||||||
|
container_path(root, target))
|
||||||
|
probe(target, "video")
|
||||||
|
probe(target, "audio")
|
||||||
|
|
||||||
|
|
||||||
|
def download_video(root, url, job_id):
|
||||||
|
video_url(url)
|
||||||
|
if not job_id or not NAME.fullmatch(job_id):
|
||||||
|
raise ValueError("Invalid job ID")
|
||||||
|
if shutil.which("yt-dlp") is None:
|
||||||
|
raise RuntimeError("yt-dlp is required for URL downloads")
|
||||||
|
prefix = f"download-{job_id}"
|
||||||
|
destination = root / "input" / f"{prefix}.mp4"
|
||||||
|
if list((root / "input").glob(prefix + ".*")):
|
||||||
|
raise FileExistsError(destination)
|
||||||
|
print("Downloading one video into input/ with yt-dlp", flush=True)
|
||||||
|
subprocess.run([
|
||||||
|
"yt-dlp", "--ignore-config", "--no-playlist", "--no-overwrites",
|
||||||
|
"--no-progress", "-t", "mp4", "--recode-video", "mp4",
|
||||||
|
"--output", str(root / "input" / f"{prefix}.%(ext)s"), url,
|
||||||
|
], check=True)
|
||||||
|
if not destination.is_file() or destination.is_symlink():
|
||||||
|
raise RuntimeError("yt-dlp did not produce the expected MP4 in input/")
|
||||||
|
probe(destination, "video")
|
||||||
|
return destination
|
||||||
|
|
||||||
|
|
||||||
|
def process_split(args, root, launcher, video):
|
||||||
|
probe(video, "audio")
|
||||||
|
target = root / "output" / f"{video.stem}-{args.preset}"
|
||||||
|
if target.exists():
|
||||||
|
raise FileExistsError(target)
|
||||||
|
job = root / "output" / f".{video.stem}-{args.preset}-{args.job_id}"
|
||||||
|
job.mkdir(mode=0o700)
|
||||||
|
print("Working directory:", job, flush=True)
|
||||||
|
silent = job / "video.mp4"
|
||||||
|
audio = job / "audio.wav"
|
||||||
|
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||||
|
"-i", container_path(root, video), "-map", "0:v:0", "-c:v", "copy",
|
||||||
|
"-an", "-movflags", "+faststart", container_path(root, silent))
|
||||||
|
probe(silent, "video")
|
||||||
|
if has_stream(silent, "audio"):
|
||||||
|
raise RuntimeError("Unexpected audio stream in split video")
|
||||||
|
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||||
|
"-i", container_path(root, video), "-map", "0:a:0", "-vn",
|
||||||
|
"-c:a", "pcm_s16le", container_path(root, audio))
|
||||||
|
probe(audio, "audio")
|
||||||
|
files = {"video.mp4": silent, "audio.wav": audio}
|
||||||
|
if args.preset == "split-stems":
|
||||||
|
run(launcher, "rvc", "cli", container_path(root, audio),
|
||||||
|
container_path(root, job), "--separate-only")
|
||||||
|
for stem in ("vocals", "instrumental"):
|
||||||
|
matches = list((job / stem).glob("*.wav"))
|
||||||
|
if len(matches) != 1:
|
||||||
|
raise RuntimeError(f"Expected exactly one {stem} stem")
|
||||||
|
probe(matches[0], "audio")
|
||||||
|
files[f"{stem}.wav"] = matches[0]
|
||||||
|
# Publish only after every processing step and stream check succeeded.
|
||||||
|
target.mkdir(mode=0o700)
|
||||||
|
for name, source in files.items():
|
||||||
|
os.link(source, target / name)
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def process(args, root, launcher):
|
||||||
|
video = media_file(root, args.video, video=True)
|
||||||
|
probe(video, "video")
|
||||||
|
if args.preset in ("split", "split-stems"):
|
||||||
|
return process_split(args, root, launcher, video)
|
||||||
|
if args.preset == "merge":
|
||||||
|
audio = audio_file(root, args.audio)
|
||||||
|
probe(audio, "audio")
|
||||||
|
target = output_path(root, video, "unito")
|
||||||
|
if target.exists():
|
||||||
|
raise FileExistsError(target)
|
||||||
|
mux(launcher, root, video, audio, target)
|
||||||
|
return target
|
||||||
|
|
||||||
|
suffix = "mia_voce" if args.preset == "audio-convert" else "facefusion"
|
||||||
|
target = output_path(root, video, suffix, "wav" if args.preset == "audio-convert" else "mp4")
|
||||||
|
if target.exists():
|
||||||
|
raise FileExistsError(target)
|
||||||
|
job = root / "output" / f".{video.stem}-{suffix}-{args.job_id}"
|
||||||
|
job.mkdir(mode=0o700)
|
||||||
|
print("Working directory:", job, flush=True)
|
||||||
|
if args.preset == "audio-convert":
|
||||||
|
probe(video, "audio")
|
||||||
|
extracted = job / "audio.wav"
|
||||||
|
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||||
|
"-i", container_path(root, video), "-vn", "-c:a", "pcm_s16le",
|
||||||
|
container_path(root, extracted))
|
||||||
|
run(launcher, "rvc", "cli", container_path(root, extracted), container_path(root, job))
|
||||||
|
instrumental = list((job / "instrumental").glob("*.wav"))
|
||||||
|
if len(instrumental) != 1:
|
||||||
|
raise RuntimeError("Expected exactly one instrumental stem")
|
||||||
|
converted = job / "vocals-mia_voce.wav"
|
||||||
|
probe(converted, "audio")
|
||||||
|
mixed = job / "mix.wav"
|
||||||
|
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||||
|
"-i", container_path(root, instrumental[0]),
|
||||||
|
"-i", container_path(root, converted),
|
||||||
|
"-filter_complex", "[0:a][1:a]amix=inputs=2:duration=longest:normalize=0[a]",
|
||||||
|
"-map", "[a]", "-c:a", "pcm_s16le", container_path(root, mixed))
|
||||||
|
probe(mixed, "audio")
|
||||||
|
os.link(mixed, target)
|
||||||
|
else:
|
||||||
|
original_has_audio = has_stream(video, "audio")
|
||||||
|
sources = [media_file(root, name) for name in SOURCE_NAMES]
|
||||||
|
processed = job / "swapped.mp4"
|
||||||
|
run(launcher, "facefusion", "cli", "headless-run",
|
||||||
|
"--source-paths", *[container_path(root, path) for path in sources],
|
||||||
|
"--target-path", container_path(root, video),
|
||||||
|
"--output-path", container_path(root, processed),
|
||||||
|
"--processors", "face_swapper", "--face-swapper-model", "hyperswap_1a_256",
|
||||||
|
"--face-swapper-pixel-boost", "256x256", "--face-swapper-weight", "0.5",
|
||||||
|
"--face-detector-model", "yolo_face", "--face-detector-size", "640x640",
|
||||||
|
"--face-detector-angles", "0", "90", "180", "270",
|
||||||
|
"--face-detector-score", "0.5", "--face-selector-mode", "one",
|
||||||
|
"--face-selector-order", "large-small", "--face-selector-gender", "female",
|
||||||
|
"--face-selector-race", "white",
|
||||||
|
"--face-mask-types", "occlusion", "region", "area", "box",
|
||||||
|
"--face-occluder-model", "xseg_1",
|
||||||
|
"--face-parser-model", "bisenet_resnet_34", "--face-mask-blur", "0.3",
|
||||||
|
"--output-video-encoder", "libx264", "--output-video-preset", "veryfast",
|
||||||
|
"--output-video-quality", "80", "--output-video-fps", "30",
|
||||||
|
"--execution-providers", "cpu", "--output-audio-encoder", "aac",
|
||||||
|
"--jobs-path", "/work/state", "--temp-path", "/work/state/tmp")
|
||||||
|
probe(processed, "video")
|
||||||
|
if abs(duration(processed) - duration(video)) > 0.5:
|
||||||
|
raise RuntimeError("FaceFusion output duration differs from the input; refusing a partial result")
|
||||||
|
if original_has_audio:
|
||||||
|
# Restore the original soundtrack explicitly. Some completed
|
||||||
|
# FaceFusion jobs have produced video-only MP4 files.
|
||||||
|
mux(launcher, root, processed, video, target)
|
||||||
|
else:
|
||||||
|
run(launcher, "ffmpeg", "-hide_banner", "-loglevel", "error", "-n",
|
||||||
|
"-i", container_path(root, processed), "-map", "0:v:0",
|
||||||
|
"-c:v", "copy", "-an", "-movflags", "+faststart",
|
||||||
|
container_path(root, target))
|
||||||
|
probe(target, "video")
|
||||||
|
if has_stream(target, "audio"):
|
||||||
|
raise RuntimeError("Unexpected audio stream in silent FaceFusion output")
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def process_complete(args, root, launcher):
|
||||||
|
video = media_file(root, args.video, video=True)
|
||||||
|
if not has_stream(video, "audio"):
|
||||||
|
raise RuntimeError("The video has no audio to convert")
|
||||||
|
common = {"video": video.name, "job_id": args.job_id}
|
||||||
|
audio = process(argparse.Namespace(preset="audio-convert", **common), root, launcher)
|
||||||
|
swapped = process(argparse.Namespace(preset="video-convert", **common), root, launcher)
|
||||||
|
target = output_path(root, video, "completo")
|
||||||
|
if target.exists():
|
||||||
|
raise FileExistsError(target)
|
||||||
|
mux(launcher, root, swapped, audio, target)
|
||||||
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(prog="ai-media preset")
|
||||||
|
parser.add_argument("root", type=Path, help=argparse.SUPPRESS)
|
||||||
|
parser.add_argument("launcher", type=Path, help=argparse.SUPPRESS)
|
||||||
|
parser.add_argument("--run", action="store_true", help=argparse.SUPPRESS)
|
||||||
|
parser.add_argument("--job-id", help=argparse.SUPPRESS)
|
||||||
|
sub = parser.add_subparsers(dest="preset", required=True)
|
||||||
|
for name in ("audio-convert", "video-convert", "merge", "split", "split-stems", "convert"):
|
||||||
|
command = sub.add_parser(name)
|
||||||
|
command.add_argument("video", help="MP4 filename inside input/ or HTTP(S) video URL")
|
||||||
|
if name == "merge":
|
||||||
|
command.add_argument("audio", help="unique audio filename in input/ or output/")
|
||||||
|
mix = sub.add_parser("mix", help="mix vocal and instrumental audio into one WAV")
|
||||||
|
mix.add_argument("vocals", help="vocal audio path relative to input/ or output/")
|
||||||
|
mix.add_argument("instrumental", help="instrumental audio path relative to input/ or output/")
|
||||||
|
mix.add_argument("--output", help="WAV filename in output/ (default: <vocals>-mix.wav)")
|
||||||
|
voice = sub.add_parser("voice-convert", help="apply mia_voce directly to an audio file")
|
||||||
|
voice.add_argument("audio", help="audio path relative to input/ or output/")
|
||||||
|
voice.add_argument("--output", help="WAV filename in output/ (default: <audio>-mia_voce.wav)")
|
||||||
|
args = parser.parse_args()
|
||||||
|
root = args.root.resolve(strict=True)
|
||||||
|
launcher = args.launcher.resolve(strict=True)
|
||||||
|
audio_only = args.preset in ("mix", "voice-convert")
|
||||||
|
remote_video = not audio_only and not NAME.fullmatch(args.video)
|
||||||
|
if args.preset == "voice-convert":
|
||||||
|
source = audio_file(root, args.audio)
|
||||||
|
wav_target(root, args.output or f"{source.stem}-mia_voce.wav")
|
||||||
|
preset_inputs = [args.audio]
|
||||||
|
if args.output:
|
||||||
|
preset_inputs += ["--output", args.output]
|
||||||
|
elif args.preset == "mix":
|
||||||
|
audio_file(root, args.vocals)
|
||||||
|
audio_file(root, args.instrumental)
|
||||||
|
mix_target(root, args)
|
||||||
|
preset_inputs = [args.vocals, args.instrumental]
|
||||||
|
if args.output:
|
||||||
|
preset_inputs += ["--output", args.output]
|
||||||
|
elif remote_video:
|
||||||
|
video_url(args.video)
|
||||||
|
if shutil.which("yt-dlp") is None:
|
||||||
|
raise RuntimeError("yt-dlp is required for URL downloads")
|
||||||
|
else:
|
||||||
|
media_file(root, args.video, video=True)
|
||||||
|
if not audio_only:
|
||||||
|
preset_inputs = [args.video] + ([args.audio] if args.preset == "merge" else [])
|
||||||
|
if args.preset == "merge":
|
||||||
|
audio_file(root, args.audio)
|
||||||
|
if args.preset in ("video-convert", "convert"):
|
||||||
|
for name in SOURCE_NAMES:
|
||||||
|
media_file(root, name)
|
||||||
|
if args.run:
|
||||||
|
if remote_video:
|
||||||
|
args.video = download_video(root, args.video, args.job_id).name
|
||||||
|
if args.preset == "voice-convert":
|
||||||
|
result = process_voice(args, root, launcher)
|
||||||
|
elif args.preset == "mix":
|
||||||
|
result = process_mix(args, root, launcher)
|
||||||
|
else:
|
||||||
|
result = (process_complete(args, root, launcher)
|
||||||
|
if args.preset == "convert" else process(args, root, launcher))
|
||||||
|
print("Completed:", result, flush=True)
|
||||||
|
return
|
||||||
|
unit = "ai-media-preset-" + datetime.now().strftime("%Y%m%d-%H%M%S") + "-" + uuid.uuid4().hex[:8]
|
||||||
|
subprocess.run(["systemd-run", "--user", "--collect", f"--unit={unit}",
|
||||||
|
"--property=Type=exec", "--property=Restart=no",
|
||||||
|
"/usr/bin/python3", str(Path(__file__).resolve()), str(root), str(launcher),
|
||||||
|
"--run", "--job-id", unit, args.preset,
|
||||||
|
*preset_inputs], check=True)
|
||||||
|
print("Job:", unit)
|
||||||
|
print("Logs: journalctl --user -fu", unit)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
main()
|
||||||
|
except (ValueError, FileNotFoundError, FileExistsError, subprocess.CalledProcessError) as error:
|
||||||
|
raise SystemExit(str(error)) from error
|
||||||
94
ansible/roles/desktop_ai_media/files/preset_rvc.py
Normal file
94
ansible/roles/desktop_ai_media/files/preset_rvc.py
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
"""Offline RVC worker for the voice preset (runs inside the RVC container)."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("input_wav", type=Path)
|
||||||
|
parser.add_argument("job_dir", type=Path)
|
||||||
|
mode = parser.add_mutually_exclusive_group()
|
||||||
|
mode.add_argument("--separate-only", action="store_true")
|
||||||
|
mode.add_argument("--convert-only", action="store_true")
|
||||||
|
args = parser.parse_args()
|
||||||
|
source = args.input_wav.resolve(strict=True)
|
||||||
|
job = args.job_dir.resolve(strict=True)
|
||||||
|
output = Path("/work/output").resolve(strict=True)
|
||||||
|
if not source.is_relative_to(output) or not job.is_relative_to(output):
|
||||||
|
raise ValueError("RVC preset paths must be inside /work/output")
|
||||||
|
if source.parent != job or not source.is_file():
|
||||||
|
raise ValueError("Expected the extracted WAV inside the job directory")
|
||||||
|
|
||||||
|
weights = Path("/work/state/weights/mia_voce.pth")
|
||||||
|
index = Path("/work/state/mia_voce/added_IVF256_Flat_nprobe_1_mia_voce_v2.index")
|
||||||
|
if not args.separate_only and not weights.is_file():
|
||||||
|
raise FileNotFoundError(weights)
|
||||||
|
if not args.separate_only and not index.is_file():
|
||||||
|
raise FileNotFoundError(index)
|
||||||
|
os.environ.update(
|
||||||
|
weight_root="/work/state/weights",
|
||||||
|
outside_index_root="/work/models/indices",
|
||||||
|
index_root="/work/state",
|
||||||
|
weight_pymss_root="/opt/app/assets/pymss_weights",
|
||||||
|
rmvpe_root="/opt/app/assets/rmvpe",
|
||||||
|
OMP_NUM_THREADS="4",
|
||||||
|
MKL_NUM_THREADS="4",
|
||||||
|
)
|
||||||
|
|
||||||
|
# The pinned WebUI imports its own argparse configuration at module load.
|
||||||
|
sys.argv = sys.argv[:1]
|
||||||
|
vocal_source = source
|
||||||
|
if not args.convert_only:
|
||||||
|
from tools.pymss_webui import pymss_separate
|
||||||
|
|
||||||
|
vocals_dir = job / "vocals"
|
||||||
|
instrumental_dir = job / "instrumental"
|
||||||
|
vocals_dir.mkdir()
|
||||||
|
instrumental_dir.mkdir()
|
||||||
|
failures = []
|
||||||
|
|
||||||
|
def on_event(event):
|
||||||
|
if event.get("event") in ("fatal", "cancelled", "busy"):
|
||||||
|
failures.append(event.get("message", str(event)))
|
||||||
|
|
||||||
|
for progress in pymss_separate(
|
||||||
|
"vocals-bs-roformer-368", str(source), str(vocals_dir), None,
|
||||||
|
str(instrumental_dir), "wav", event_callback=on_event,
|
||||||
|
):
|
||||||
|
print(progress, flush=True)
|
||||||
|
if failures:
|
||||||
|
raise RuntimeError("RVC separation failed: " + "; ".join(failures))
|
||||||
|
vocals = list(vocals_dir.glob("*.wav"))
|
||||||
|
instrumental = list(instrumental_dir.glob("*.wav"))
|
||||||
|
if len(vocals) != 1 or len(instrumental) != 1:
|
||||||
|
raise RuntimeError("RVC did not produce exactly one vocal and instrumental stem")
|
||||||
|
|
||||||
|
if args.separate_only:
|
||||||
|
print("Vocal and instrumental stems ready (no voice conversion)", flush=True)
|
||||||
|
return
|
||||||
|
|
||||||
|
vocal_source = vocals[0]
|
||||||
|
|
||||||
|
from configs.config import Config
|
||||||
|
from infer.vc.modules import VC
|
||||||
|
import soundfile as sf
|
||||||
|
|
||||||
|
voice = VC(Config())
|
||||||
|
voice.get_vc(weights.name)
|
||||||
|
status, result = voice.vc_single(
|
||||||
|
0, str(vocal_source), 0, "rmvpe", str(index), 0.75, 0, 1, 0.33,
|
||||||
|
)
|
||||||
|
if result is None or result[0] is None or result[1] is None:
|
||||||
|
raise RuntimeError("RVC voice conversion failed: " + str(status))
|
||||||
|
converted = job / "vocals-mia_voce.wav"
|
||||||
|
sf.write(converted, result[1], result[0])
|
||||||
|
if converted.stat().st_size == 0:
|
||||||
|
raise RuntimeError("RVC produced an empty converted voice")
|
||||||
|
print("RVC converted voice ready", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -84,6 +84,14 @@
|
|||||||
loop: [session.py, prepare.py, verify.py, check_storage.py]
|
loop: [session.py, prepare.py, verify.py, check_storage.py]
|
||||||
register: desktop_ai_media_support
|
register: desktop_ai_media_support
|
||||||
|
|
||||||
|
- name: Install host-side offline preset workers without rebuilding images
|
||||||
|
tags: [ai_media_presets]
|
||||||
|
ansible.builtin.copy:
|
||||||
|
src: "{{ item }}"
|
||||||
|
dest: "{{ desktop_ai_media_build_root }}/{{ item }}"
|
||||||
|
mode: "0644"
|
||||||
|
loop: [preset.py, preset_rvc.py]
|
||||||
|
|
||||||
- name: Create public model cache directories
|
- name: Create public model cache directories
|
||||||
ansible.builtin.file:
|
ansible.builtin.file:
|
||||||
path: "{{ desktop_ai_media_build_root }}/models/{{ item.app }}/{{ item.path | dirname }}"
|
path: "{{ desktop_ai_media_build_root }}/models/{{ item.app }}/{{ item.path | dirname }}"
|
||||||
|
|||||||
@@ -1,10 +1,20 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
root={{ desktop_ai_media_root | quote }}
|
root={{ desktop_ai_media_root | quote }}
|
||||||
|
build_root={{ desktop_ai_media_build_root | quote }}
|
||||||
app="${1:-}"
|
app="${1:-}"
|
||||||
case "$app" in
|
case "$app" in
|
||||||
facefusion|rvc) shift ;;
|
facefusion|rvc) shift ;;
|
||||||
ffmpeg) app=facefusion; shift; set -- ffmpeg "$@" ;;
|
ffmpeg) app=facefusion; shift; set -- ffmpeg "$@" ;;
|
||||||
|
preset)
|
||||||
|
shift
|
||||||
|
for path in "$root" "$root/input" "$root/output"; do
|
||||||
|
[[ -d "$path" && "$(realpath -- "$path")" == "$path" ]] || {
|
||||||
|
echo "Unsafe or missing media directory: $path" >&2; exit 1;
|
||||||
|
}
|
||||||
|
done
|
||||||
|
python3 "$build_root/check_storage.py" "$root"
|
||||||
|
exec python3 "$build_root/preset.py" "$root" "$(realpath -- "$0")" "$@" ;;
|
||||||
verify)
|
verify)
|
||||||
for tool in facefusion rvc; do
|
for tool in facefusion rvc; do
|
||||||
podman --remote=false run --rm --pull=never --network=none --read-only \
|
podman --remote=false run --rm --pull=never --network=none --read-only \
|
||||||
@@ -17,7 +27,7 @@ case "$app" in
|
|||||||
"localhost/ai-media-$tool:managed" verify
|
"localhost/ai-media-$tool:managed" verify
|
||||||
done
|
done
|
||||||
exit 0 ;;
|
exit 0 ;;
|
||||||
*) echo "Usage: ai-media {facefusion|rvc|ffmpeg|verify} [cli ...]" >&2; exit 2 ;;
|
*) echo "Usage: ai-media {facefusion|rvc|ffmpeg|preset|verify} [args ...]" >&2; exit 2 ;;
|
||||||
esac
|
esac
|
||||||
# Fail closed if an existing data path was replaced by a symlink.
|
# Fail closed if an existing data path was replaced by a symlink.
|
||||||
for path in "$root" "$root/input" "$root/output" "$root/models" "$root/state/$app"; do
|
for path in "$root" "$root/input" "$root/output" "$root/models" "$root/state/$app"; do
|
||||||
@@ -45,6 +55,13 @@ fi
|
|||||||
if [[ "${1:-}" == --foreground ]]; then
|
if [[ "${1:-}" == --foreground ]]; then
|
||||||
shift
|
shift
|
||||||
fi
|
fi
|
||||||
|
if [[ "$app" == rvc && "${1:-}" == cli ]]; then
|
||||||
|
shift
|
||||||
|
rvc_cli=1
|
||||||
|
set -- /opt/preset_rvc.py "$@"
|
||||||
|
else
|
||||||
|
rvc_cli=0
|
||||||
|
fi
|
||||||
args=(
|
args=(
|
||||||
run --rm --pull=never --network=none --read-only --userns=keep-id --http-proxy=false
|
run --rm --pull=never --network=none --read-only --userns=keep-id --http-proxy=false
|
||||||
--cap-drop=ALL --security-opt=no-new-privileges
|
--cap-drop=ALL --security-opt=no-new-privileges
|
||||||
@@ -56,7 +73,10 @@ args=(
|
|||||||
--volume "$root/models:/work/models:ro,Z"
|
--volume "$root/models:/work/models:ro,Z"
|
||||||
--volume "$root/state/$app:/work/state:rw,Z"
|
--volume "$root/state/$app:/work/state:rw,Z"
|
||||||
)
|
)
|
||||||
if [[ "${1:-}" != cli && "${1:-}" != ffmpeg ]]; then
|
if [[ "$rvc_cli" == 1 ]]; then
|
||||||
|
args+=(--volume "$build_root/preset_rvc.py:/opt/preset_rvc.py:ro,Z" --entrypoint python)
|
||||||
|
fi
|
||||||
|
if [[ "$rvc_cli" != 1 && "${1:-}" != cli && "${1:-}" != ffmpeg ]]; then
|
||||||
: "${XDG_RUNTIME_DIR:?Run this launcher from the GNOME Wayland session}"
|
: "${XDG_RUNTIME_DIR:?Run this launcher from the GNOME Wayland session}"
|
||||||
: "${WAYLAND_DISPLAY:?A Wayland session is required}"
|
: "${WAYLAND_DISPLAY:?A Wayland session is required}"
|
||||||
[[ "$WAYLAND_DISPLAY" != */* && -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]] || exit 1
|
[[ "$WAYLAND_DISPLAY" != */* && -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]] || exit 1
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import socket
|
|||||||
import subprocess
|
import subprocess
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
|
import wave
|
||||||
|
import struct
|
||||||
|
|
||||||
from jinja2 import Environment
|
from jinja2 import Environment
|
||||||
import shlex
|
import shlex
|
||||||
@@ -27,6 +29,8 @@ class LauncherTest(unittest.TestCase):
|
|||||||
(ROLE / 'templates/ai-media.j2').read_text()
|
(ROLE / 'templates/ai-media.j2').read_text()
|
||||||
).render(desktop_ai_media_root=str(self.media), desktop_ai_media_build_root=str(self.root)))
|
).render(desktop_ai_media_root=str(self.media), desktop_ai_media_build_root=str(self.root)))
|
||||||
(self.root / 'check_storage.py').write_text((ROLE / 'files/check_storage.py').read_text())
|
(self.root / 'check_storage.py').write_text((ROLE / 'files/check_storage.py').read_text())
|
||||||
|
for name in ('preset.py', 'preset_rvc.py'):
|
||||||
|
(self.root / name).write_text((ROLE / 'files' / name).read_text())
|
||||||
self.log = self.root / 'podman.json'
|
self.log = self.root / 'podman.json'
|
||||||
podman = self.root / 'podman'
|
podman = self.root / 'podman'
|
||||||
podman.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
podman.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||||
@@ -39,6 +43,207 @@ class LauncherTest(unittest.TestCase):
|
|||||||
return subprocess.run(['bash', str(self.launcher), *args], env=self.env,
|
return subprocess.run(['bash', str(self.launcher), *args], env=self.env,
|
||||||
capture_output=True, text=True)
|
capture_output=True, text=True)
|
||||||
|
|
||||||
|
def fake_media_launcher(self):
|
||||||
|
fake = self.root / 'fake-ai-media'
|
||||||
|
fake.write_text('''#!/usr/bin/python3
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
|
||||||
|
root = Path(os.environ["TEST_MEDIA"])
|
||||||
|
def host(path):
|
||||||
|
return str(path).replace("/work/input/", str(root / "input") + "/").replace(
|
||||||
|
"/work/output/", str(root / "output") + "/")
|
||||||
|
|
||||||
|
tool = sys.argv[1]
|
||||||
|
args = sys.argv[2:]
|
||||||
|
if tool == "ffmpeg":
|
||||||
|
os.execvp("ffmpeg", ["ffmpeg", *[host(arg) for arg in args]])
|
||||||
|
if tool == "facefusion":
|
||||||
|
(root / "facefusion-args.json").write_text(__import__("json").dumps(args))
|
||||||
|
shutil.copyfile(host(args[args.index("--target-path") + 1]),
|
||||||
|
host(args[args.index("--output-path") + 1]))
|
||||||
|
raise SystemExit(0)
|
||||||
|
if tool == "rvc":
|
||||||
|
(root / "rvc-args.json").write_text(__import__("json").dumps(args))
|
||||||
|
source = Path(host(args[1]))
|
||||||
|
job = Path(host(args[2]))
|
||||||
|
if "--convert-only" not in args:
|
||||||
|
(job / "instrumental").mkdir()
|
||||||
|
shutil.copyfile(source, job / "instrumental/stem.wav")
|
||||||
|
if "--separate-only" in args:
|
||||||
|
(job / "vocals").mkdir()
|
||||||
|
shutil.copyfile(source, job / "vocals/stem.wav")
|
||||||
|
else:
|
||||||
|
shutil.copyfile(source, job / "vocals-mia_voce.wav")
|
||||||
|
raise SystemExit(0)
|
||||||
|
raise SystemExit("Unexpected tool: " + tool)
|
||||||
|
''')
|
||||||
|
fake.chmod(0o755)
|
||||||
|
return fake
|
||||||
|
|
||||||
|
def fake_downloader(self, fixture):
|
||||||
|
downloader = self.root / 'yt-dlp'
|
||||||
|
downloader.write_text('''#!/usr/bin/python3
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
|
||||||
|
args = sys.argv[1:]
|
||||||
|
Path(os.environ["TEST_LOG"]).write_text(json.dumps(args))
|
||||||
|
destination = args[args.index("--output") + 1].replace("%(ext)s", "mp4")
|
||||||
|
shutil.copyfile(os.environ["TEST_DOWNLOAD_FIXTURE"], destination)
|
||||||
|
''')
|
||||||
|
downloader.chmod(0o755)
|
||||||
|
self.env['TEST_DOWNLOAD_FIXTURE'] = str(fixture)
|
||||||
|
return downloader
|
||||||
|
|
||||||
|
def run_preset(self, fake, *args, job_id='test'):
|
||||||
|
return subprocess.run(['python3', str(self.root / 'preset.py'),
|
||||||
|
str(self.media), str(fake), '--run', '--job-id', job_id, *args],
|
||||||
|
env={**self.env, 'TEST_MEDIA': str(self.media)},
|
||||||
|
capture_output=True, text=True)
|
||||||
|
|
||||||
|
def create_video(self, *, audio=False):
|
||||||
|
video = self.media / 'input/video1.mp4'
|
||||||
|
command = ['ffmpeg', '-hide_banner', '-loglevel', 'error', '-f', 'lavfi',
|
||||||
|
'-i', 'color=c=black:s=64x64:d=1']
|
||||||
|
if audio:
|
||||||
|
command += ['-f', 'lavfi', '-i', 'sine=frequency=440:duration=1']
|
||||||
|
command += ['-c:v', 'mpeg4']
|
||||||
|
if audio:
|
||||||
|
command += ['-c:a', 'aac', '-shortest']
|
||||||
|
subprocess.run([*command, str(video)], check=True)
|
||||||
|
return video
|
||||||
|
|
||||||
|
def stream_types(self, path):
|
||||||
|
probe = subprocess.check_output(['ffprobe', '-v', 'error', '-show_entries',
|
||||||
|
'stream=codec_type', '-of', 'json', str(path)])
|
||||||
|
return {stream['codec_type'] for stream in json.loads(probe)['streams']}
|
||||||
|
|
||||||
|
def create_audio(self, relative, sample=1000, seconds=1):
|
||||||
|
path = self.media / relative
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with wave.open(str(path), 'wb') as audio:
|
||||||
|
audio.setparams((1, 2, 8000, 0, 'NONE', 'not compressed'))
|
||||||
|
audio.writeframes(struct.pack('<h', sample) * (8000 * seconds))
|
||||||
|
return path
|
||||||
|
|
||||||
|
def test_mix_sums_stems_and_preserves_longest_duration(self):
|
||||||
|
vocals = self.create_audio('output/video1-split-stems/vocals.wav')
|
||||||
|
instrumental = self.create_audio('output/video1-split-stems/instrumental.wav',
|
||||||
|
sample=2000, seconds=2)
|
||||||
|
before = [path.read_bytes() for path in (vocals, instrumental)]
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), 'mix',
|
||||||
|
'video1-split-stems/vocals.wav',
|
||||||
|
'video1-split-stems/instrumental.wav', '--output', 'song.wav')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
output = self.media / 'output/song.wav'
|
||||||
|
self.assertEqual(self.stream_types(output), {'audio'})
|
||||||
|
with wave.open(str(output), 'rb') as audio:
|
||||||
|
self.assertEqual(audio.getnframes(), 16000)
|
||||||
|
samples = struct.unpack('<16000h', audio.readframes(16000))
|
||||||
|
self.assertAlmostEqual(samples[4000], 3000, delta=1)
|
||||||
|
self.assertAlmostEqual(samples[12000], 2000, delta=1)
|
||||||
|
self.assertEqual([path.read_bytes() for path in (vocals, instrumental)], before)
|
||||||
|
|
||||||
|
def test_voice_convert_audio_skips_separation_and_preserves_input(self):
|
||||||
|
source = self.create_audio('output/video1-split-stems/vocals.wav')
|
||||||
|
before = source.read_bytes()
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), 'voice-convert',
|
||||||
|
'video1-split-stems/vocals.wav')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
output = self.media / 'output/vocals-mia_voce.wav'
|
||||||
|
self.assertEqual(self.stream_types(output), {'audio'})
|
||||||
|
args = json.loads((self.media / 'rvc-args.json').read_text())
|
||||||
|
self.assertIn('--convert-only', args)
|
||||||
|
self.assertFalse(list((self.media / 'output').rglob('instrumental')))
|
||||||
|
self.assertFalse((self.media / 'facefusion-args.json').exists())
|
||||||
|
self.assertEqual(source.read_bytes(), before)
|
||||||
|
repeated = self.run_preset(self.fake_media_launcher(), 'voice-convert',
|
||||||
|
'video1-split-stems/vocals.wav')
|
||||||
|
self.assertNotEqual(repeated.returncode, 0)
|
||||||
|
|
||||||
|
def test_voice_convert_dispatches_with_custom_output(self):
|
||||||
|
self.create_audio('input/voice.wav')
|
||||||
|
runner = self.root / 'systemd-run'
|
||||||
|
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||||
|
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
|
||||||
|
runner.chmod(0o755)
|
||||||
|
result = self.launch('preset', 'voice-convert', 'voice.wav', '--output', 'mine.wav')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
args = json.loads(self.log.read_text())
|
||||||
|
self.assertIn('--user', args)
|
||||||
|
self.assertEqual(args[-4:], ['voice-convert', 'voice.wav', '--output', 'mine.wav'])
|
||||||
|
|
||||||
|
def test_voice_convert_rejects_invalid_audio_and_output(self):
|
||||||
|
self.create_audio('input/voice.wav')
|
||||||
|
for name in ('missing.wav', '../voice.wav', 'https://example.org/audio.wav'):
|
||||||
|
self.assertNotEqual(self.launch('preset', 'voice-convert', name).returncode, 0)
|
||||||
|
for name in ('../mine.wav', 'mine.mp3'):
|
||||||
|
self.assertNotEqual(self.launch('preset', 'voice-convert', 'voice.wav',
|
||||||
|
'--output', name).returncode, 0)
|
||||||
|
self.create_audio('output/voice.wav')
|
||||||
|
self.assertNotEqual(self.launch('preset', 'voice-convert', 'voice.wav').returncode, 0)
|
||||||
|
self.assertFalse(self.log.exists())
|
||||||
|
|
||||||
|
def test_mix_default_output_and_no_overwrite(self):
|
||||||
|
self.create_audio('input/voice.wav')
|
||||||
|
self.create_audio('output/instrumental.wav')
|
||||||
|
args = ('mix', 'voice.wav', 'instrumental.wav')
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), *args)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
target = self.media / 'output/voice-mix.wav'
|
||||||
|
original = target.read_bytes()
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), *args)
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
self.assertEqual(target.read_bytes(), original)
|
||||||
|
|
||||||
|
def test_mix_dispatches_audio_only_background_job(self):
|
||||||
|
self.create_audio('input/voice.wav')
|
||||||
|
self.create_audio('output/instrumental.wav')
|
||||||
|
runner = self.root / 'systemd-run'
|
||||||
|
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||||
|
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
|
||||||
|
runner.chmod(0o755)
|
||||||
|
result = self.launch('preset', 'mix', 'voice.wav', 'instrumental.wav',
|
||||||
|
'--output', 'song.wav')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
args = json.loads(self.log.read_text())
|
||||||
|
self.assertIn('--user', args)
|
||||||
|
self.assertEqual(args[-5:], ['mix', 'voice.wav', 'instrumental.wav',
|
||||||
|
'--output', 'song.wav'])
|
||||||
|
self.assertFalse((self.media / 'output/song.wav').exists())
|
||||||
|
|
||||||
|
def test_mix_rejects_unsafe_paths_and_ambiguous_audio(self):
|
||||||
|
self.create_audio('input/voice.wav')
|
||||||
|
self.create_audio('output/instrumental.wav')
|
||||||
|
for unsafe in ('../voice.wav', '/tmp/voice.wav', 'https://example.org/voice.wav'):
|
||||||
|
result = self.launch('preset', 'mix', unsafe, 'instrumental.wav')
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
for unsafe in ('../song.wav', '/tmp/song.wav', 'song.mp3'):
|
||||||
|
result = self.launch('preset', 'mix', 'voice.wav', 'instrumental.wav',
|
||||||
|
'--output', unsafe)
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
(self.media / 'output/linked').symlink_to(self.media / 'input', target_is_directory=True)
|
||||||
|
self.assertNotEqual(self.launch('preset', 'mix', 'linked/voice.wav',
|
||||||
|
'instrumental.wav').returncode, 0)
|
||||||
|
self.create_audio('output/voice.wav')
|
||||||
|
self.assertNotEqual(self.launch('preset', 'mix', 'voice.wav',
|
||||||
|
'instrumental.wav').returncode, 0)
|
||||||
|
self.assertFalse(self.log.exists())
|
||||||
|
|
||||||
|
def test_mix_rejects_missing_audio_stream(self):
|
||||||
|
video = self.create_video()
|
||||||
|
self.create_audio('output/instrumental.wav')
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), 'mix', video.name,
|
||||||
|
'instrumental.wav')
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
self.assertFalse((self.media / 'output/video1-mix.wav').exists())
|
||||||
|
|
||||||
def test_cli_has_no_network_or_host_home(self):
|
def test_cli_has_no_network_or_host_home(self):
|
||||||
result = self.launch('facefusion', 'cli', '--help')
|
result = self.launch('facefusion', 'cli', '--help')
|
||||||
self.assertEqual(result.returncode, 0, result.stderr)
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
@@ -65,6 +270,211 @@ class LauncherTest(unittest.TestCase):
|
|||||||
self.assertNotIn('--publish', args)
|
self.assertNotIn('--publish', args)
|
||||||
self.assertFalse(any('dbus' in arg for arg in args))
|
self.assertFalse(any('dbus' in arg for arg in args))
|
||||||
|
|
||||||
|
def test_rvc_cli_is_offline_and_mounts_only_preset_code(self):
|
||||||
|
result = self.launch('rvc', 'cli', '/work/output/job/audio.wav', '/work/output/job')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
args = json.loads(self.log.read_text())
|
||||||
|
self.assertIn('--network=none', args)
|
||||||
|
self.assertIn('--entrypoint', args)
|
||||||
|
self.assertIn('python', args)
|
||||||
|
self.assertIn(str(self.root / 'preset_rvc.py') + ':/opt/preset_rvc.py:ro,Z', args)
|
||||||
|
self.assertIn('/opt/preset_rvc.py', args)
|
||||||
|
self.assertNotIn('label=disable', args)
|
||||||
|
|
||||||
|
def test_voice_preset_dispatches_to_user_service(self):
|
||||||
|
(self.media / 'input/video1.mp4').write_bytes(b'not processed in dispatch')
|
||||||
|
runner = self.root / 'systemd-run'
|
||||||
|
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||||
|
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
|
||||||
|
runner.chmod(0o755)
|
||||||
|
result = self.launch('preset', 'audio-convert', 'video1.mp4')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
args = json.loads(self.log.read_text())
|
||||||
|
self.assertIn('--user', args)
|
||||||
|
self.assertIn('--property=Restart=no', args)
|
||||||
|
self.assertIn('audio-convert', args)
|
||||||
|
self.assertIn('video1.mp4', args)
|
||||||
|
|
||||||
|
def test_face_preset_requires_all_sources(self):
|
||||||
|
(self.media / 'input/video1.mp4').write_bytes(b'video')
|
||||||
|
self.assertNotEqual(self.launch('preset', 'video-convert', 'video1.mp4').returncode, 0)
|
||||||
|
self.assertFalse(self.log.exists())
|
||||||
|
|
||||||
|
def test_complete_preset_rejects_local_url(self):
|
||||||
|
result = self.launch('preset', 'convert', 'file:///tmp/video.mp4')
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
self.assertFalse(self.log.exists())
|
||||||
|
|
||||||
|
def test_old_preset_names_are_rejected(self):
|
||||||
|
for name in ('voce', 'volti', 'unisci', 'completo'):
|
||||||
|
with self.subTest(name=name):
|
||||||
|
self.assertEqual(self.launch('preset', name, 'video1.mp4').returncode, 2)
|
||||||
|
|
||||||
|
def test_all_url_presets_dispatch_one_background_job(self):
|
||||||
|
for number in range(11, 19):
|
||||||
|
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||||
|
runner = self.root / 'systemd-run'
|
||||||
|
runner.write_text('#!/usr/bin/python3\nimport json,os,sys\n'
|
||||||
|
'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n')
|
||||||
|
runner.chmod(0o755)
|
||||||
|
(self.media / 'input/audio.wav').write_bytes(b'audio')
|
||||||
|
for preset in ('audio-convert', 'video-convert', 'merge', 'split',
|
||||||
|
'split-stems', 'convert'):
|
||||||
|
with self.subTest(preset=preset):
|
||||||
|
extra = ['audio.wav'] if preset == 'merge' else []
|
||||||
|
result = self.launch('preset', preset, 'https://example.org/video', *extra)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
args = json.loads(self.log.read_text())
|
||||||
|
self.assertIn('--user', args)
|
||||||
|
self.assertIn(preset, args)
|
||||||
|
self.assertIn('https://example.org/video', args)
|
||||||
|
if extra:
|
||||||
|
self.assertEqual(args[-1], 'audio.wav')
|
||||||
|
self.assertFalse(list((self.media / 'input').glob('download-*')))
|
||||||
|
|
||||||
|
def test_mux_preset_rejects_ambiguous_audio(self):
|
||||||
|
(self.media / 'input/video1.mp4').write_bytes(b'video')
|
||||||
|
(self.media / 'input/audio.wav').write_bytes(b'audio')
|
||||||
|
(self.media / 'output/audio.wav').write_bytes(b'audio')
|
||||||
|
self.assertNotEqual(self.launch('preset', 'merge', 'video1.mp4', 'audio.wav').returncode, 0)
|
||||||
|
self.assertFalse(self.log.exists())
|
||||||
|
|
||||||
|
def test_mux_preset_creates_audio_video_with_streams(self):
|
||||||
|
if subprocess.run(['bash', '-c', 'command -v ffmpeg && command -v ffprobe'],
|
||||||
|
capture_output=True).returncode != 0:
|
||||||
|
self.skipTest('ffmpeg and ffprobe required')
|
||||||
|
self.create_video()
|
||||||
|
audio = self.media / 'input/audio.wav'
|
||||||
|
subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-f', 'lavfi',
|
||||||
|
'-i', 'sine=frequency=440:duration=1', str(audio)], check=True)
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), 'merge', 'video1.mp4', 'audio.wav')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
output = self.media / 'output/video1-unito.mp4'
|
||||||
|
self.assertTrue(output.is_file())
|
||||||
|
self.assertEqual(self.stream_types(output), {'video', 'audio'})
|
||||||
|
|
||||||
|
def test_voice_preset_outputs_audio_only(self):
|
||||||
|
self.create_video(audio=True)
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), 'audio-convert', 'video1.mp4')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
output = self.media / 'output/video1-mia_voce.wav'
|
||||||
|
self.assertEqual(self.stream_types(output), {'audio'})
|
||||||
|
self.assertFalse((self.media / 'output/video1-mia_voce.mp4').exists())
|
||||||
|
|
||||||
|
def test_split_presets_output_separate_streams_without_conversion(self):
|
||||||
|
original = self.create_video(audio=True).read_bytes()
|
||||||
|
for preset in ('split', 'split-stems'):
|
||||||
|
with self.subTest(preset=preset):
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), preset, 'video1.mp4')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
output = self.media / 'output' / f'video1-{preset}'
|
||||||
|
expected = {'video.mp4', 'audio.wav'}
|
||||||
|
if preset == 'split-stems':
|
||||||
|
expected |= {'vocals.wav', 'instrumental.wav'}
|
||||||
|
args = json.loads((self.media / 'rvc-args.json').read_text())
|
||||||
|
self.assertIn('--separate-only', args)
|
||||||
|
else:
|
||||||
|
self.assertFalse((self.media / 'rvc-args.json').exists())
|
||||||
|
self.assertEqual({p.name for p in output.iterdir()}, expected)
|
||||||
|
for name in expected:
|
||||||
|
self.assertEqual(self.stream_types(output / name),
|
||||||
|
{'video'} if name == 'video.mp4' else {'audio'})
|
||||||
|
self.assertEqual((self.media / 'input/video1.mp4').read_bytes(), original)
|
||||||
|
self.assertFalse(list((self.media / 'output').rglob('*mia_voce*')))
|
||||||
|
before = {p.name: p.read_bytes() for p in output.iterdir()}
|
||||||
|
repeated = self.run_preset(self.fake_media_launcher(), preset, 'video1.mp4',
|
||||||
|
job_id='repeat')
|
||||||
|
self.assertNotEqual(repeated.returncode, 0)
|
||||||
|
self.assertEqual({p.name: p.read_bytes() for p in output.iterdir()}, before)
|
||||||
|
|
||||||
|
def test_split_presets_reject_video_without_audio(self):
|
||||||
|
self.create_video()
|
||||||
|
for preset in ('split', 'split-stems'):
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), preset, 'video1.mp4')
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
self.assertFalse(list((self.media / 'output').iterdir()))
|
||||||
|
|
||||||
|
def test_face_preset_preserves_audio_only_when_present(self):
|
||||||
|
for audio in (False, True):
|
||||||
|
with self.subTest(audio=audio):
|
||||||
|
video = self.media / 'input/video1.mp4'
|
||||||
|
if video.exists():
|
||||||
|
video.unlink()
|
||||||
|
self.create_video(audio=audio)
|
||||||
|
for number in range(11, 19):
|
||||||
|
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||||
|
output = self.media / 'output/video1-facefusion.mp4'
|
||||||
|
if output.exists():
|
||||||
|
output.unlink()
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), 'video-convert', 'video1.mp4',
|
||||||
|
job_id=f'test-{audio}')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertEqual(self.stream_types(output),
|
||||||
|
{'video', 'audio'} if audio else {'video'})
|
||||||
|
|
||||||
|
def test_face_preset_uses_requested_options(self):
|
||||||
|
self.create_video(audio=True)
|
||||||
|
for number in range(11, 19):
|
||||||
|
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), 'video-convert', 'video1.mp4')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
args = json.loads((self.media / 'facefusion-args.json').read_text())
|
||||||
|
source_start = args.index('--source-paths') + 1
|
||||||
|
self.assertEqual(args[source_start:source_start + 8],
|
||||||
|
[f'/work/input/source{number}.jpg' for number in range(11, 19)])
|
||||||
|
expected = {
|
||||||
|
'--processors': ['face_swapper'],
|
||||||
|
'--face-swapper-model': ['hyperswap_1a_256'],
|
||||||
|
'--face-swapper-pixel-boost': ['256x256'],
|
||||||
|
'--face-swapper-weight': ['0.5'],
|
||||||
|
'--face-detector-model': ['yolo_face'],
|
||||||
|
'--face-detector-size': ['640x640'],
|
||||||
|
'--face-detector-angles': ['0', '90', '180', '270'],
|
||||||
|
'--face-detector-score': ['0.5'],
|
||||||
|
'--face-selector-mode': ['one'],
|
||||||
|
'--face-selector-order': ['large-small'],
|
||||||
|
'--face-selector-gender': ['female'],
|
||||||
|
'--face-selector-race': ['white'],
|
||||||
|
'--face-mask-types': ['occlusion', 'region', 'area', 'box'],
|
||||||
|
'--face-occluder-model': ['xseg_1'],
|
||||||
|
'--face-parser-model': ['bisenet_resnet_34'],
|
||||||
|
'--face-mask-blur': ['0.3'],
|
||||||
|
'--output-video-encoder': ['libx264'],
|
||||||
|
'--output-video-preset': ['veryfast'],
|
||||||
|
'--output-video-quality': ['80'],
|
||||||
|
'--output-video-fps': ['30'],
|
||||||
|
'--execution-providers': ['cpu'],
|
||||||
|
'--output-audio-encoder': ['aac'],
|
||||||
|
'--jobs-path': ['/work/state'],
|
||||||
|
'--temp-path': ['/work/state/tmp'],
|
||||||
|
}
|
||||||
|
for flag, values in expected.items():
|
||||||
|
with self.subTest(flag=flag):
|
||||||
|
start = args.index(flag) + 1
|
||||||
|
self.assertEqual(args[start:start + len(values)], values)
|
||||||
|
|
||||||
|
def test_complete_preset_downloads_and_combines_both_results(self):
|
||||||
|
fixture = self.create_video(audio=True)
|
||||||
|
for number in range(11, 19):
|
||||||
|
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||||
|
self.fake_downloader(fixture)
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), 'convert',
|
||||||
|
'https://example.org/video', job_id='test')
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertTrue((self.media / 'input/download-test.mp4').is_file())
|
||||||
|
self.assertEqual(self.stream_types(self.media / 'output/download-test-mia_voce.wav'),
|
||||||
|
{'audio'})
|
||||||
|
self.assertEqual(self.stream_types(self.media / 'output/download-test-facefusion.mp4'),
|
||||||
|
{'video', 'audio'})
|
||||||
|
self.assertEqual(self.stream_types(self.media / 'output/download-test-completo.mp4'),
|
||||||
|
{'video', 'audio'})
|
||||||
|
face_args = json.loads((self.media / 'facefusion-args.json').read_text())
|
||||||
|
self.assertEqual(face_args[face_args.index('--face-selector-gender') + 1], 'female')
|
||||||
|
self.assertEqual(face_args[face_args.index('--output-video-fps') + 1], '30')
|
||||||
|
downloader_args = json.loads(self.log.read_text())
|
||||||
|
self.assertIn('--ignore-config', downloader_args)
|
||||||
|
self.assertIn('--no-playlist', downloader_args)
|
||||||
|
|
||||||
def test_default_gui_uses_independent_user_service(self):
|
def test_default_gui_uses_independent_user_service(self):
|
||||||
self.env.update(XDG_RUNTIME_DIR=str(self.root), WAYLAND_DISPLAY='wayland-0')
|
self.env.update(XDG_RUNTIME_DIR=str(self.root), WAYLAND_DISPLAY='wayland-0')
|
||||||
runner = self.root / 'systemd-run'
|
runner = self.root / 'systemd-run'
|
||||||
@@ -84,6 +494,72 @@ class LauncherTest(unittest.TestCase):
|
|||||||
self.assertNotIn('--pty', args)
|
self.assertNotIn('--pty', args)
|
||||||
self.assertNotIn('--wait', args)
|
self.assertNotIn('--wait', args)
|
||||||
|
|
||||||
|
def test_all_presets_download_url_before_processing(self):
|
||||||
|
fixture = self.create_video(audio=True)
|
||||||
|
self.fake_downloader(fixture)
|
||||||
|
for number in range(11, 19):
|
||||||
|
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||||
|
audio = self.media / 'input/audio.wav'
|
||||||
|
subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-i',
|
||||||
|
str(fixture), '-vn', str(audio)], check=True)
|
||||||
|
outputs = {
|
||||||
|
'audio-convert': 'mia_voce.wav', 'video-convert': 'facefusion.mp4',
|
||||||
|
'merge': 'unito.mp4', 'split': 'split', 'split-stems': 'split-stems',
|
||||||
|
'convert': 'completo.mp4',
|
||||||
|
}
|
||||||
|
for preset, suffix in outputs.items():
|
||||||
|
with self.subTest(preset=preset):
|
||||||
|
extra = ['audio.wav'] if preset == 'merge' else []
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), preset,
|
||||||
|
'https://example.org/video?a=1&b=2', *extra,
|
||||||
|
job_id=preset)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertEqual(result.stdout.count('Downloading one video'), 1)
|
||||||
|
self.assertTrue((self.media / f'input/download-{preset}.mp4').is_file())
|
||||||
|
output = self.media / f'output/download-{preset}-{suffix}'
|
||||||
|
self.assertTrue(output.exists())
|
||||||
|
if preset in ('split', 'split-stems'):
|
||||||
|
self.assertEqual(self.stream_types(output / 'video.mp4'), {'video'})
|
||||||
|
self.assertEqual(self.stream_types(output / 'audio.wav'), {'audio'})
|
||||||
|
else:
|
||||||
|
self.assertEqual(self.stream_types(output), {'audio'} if
|
||||||
|
preset == 'audio-convert' else {'video', 'audio'})
|
||||||
|
download_args = json.loads(self.log.read_text())
|
||||||
|
self.assertEqual(download_args[-1], 'https://example.org/video?a=1&b=2')
|
||||||
|
for flag in ('--ignore-config', '--no-playlist', '--no-overwrites'):
|
||||||
|
self.assertIn(flag, download_args)
|
||||||
|
|
||||||
|
def test_convert_also_accepts_local_video_without_download(self):
|
||||||
|
fixture = self.create_video(audio=True)
|
||||||
|
self.fake_downloader(fixture)
|
||||||
|
for number in range(11, 19):
|
||||||
|
(self.media / f'input/source{number}.jpg').write_bytes(b'source')
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), 'convert', fixture.name)
|
||||||
|
self.assertEqual(result.returncode, 0, result.stderr)
|
||||||
|
self.assertFalse(self.log.exists())
|
||||||
|
self.assertEqual(self.stream_types(self.media / 'output/video1-completo.mp4'),
|
||||||
|
{'video', 'audio'})
|
||||||
|
|
||||||
|
def test_all_presets_reject_invalid_urls_before_dispatch(self):
|
||||||
|
for preset in ('split', 'split-stems', 'audio-convert', 'video-convert',
|
||||||
|
'merge', 'convert'):
|
||||||
|
for url in ('file:///tmp/video.mp4', 'https://localhost/video',
|
||||||
|
'http://192.168.1.1/video', 'https://user:password@example.org/video'):
|
||||||
|
with self.subTest(preset=preset, url=url):
|
||||||
|
extra = ['audio.wav'] if preset == 'merge' else []
|
||||||
|
result = self.launch('preset', preset, url, *extra)
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
self.assertFalse(self.log.exists())
|
||||||
|
|
||||||
|
def test_failed_url_download_does_not_start_processing(self):
|
||||||
|
downloader = self.root / 'yt-dlp'
|
||||||
|
downloader.write_text('#!/bin/sh\nexit 1\n')
|
||||||
|
downloader.chmod(0o755)
|
||||||
|
result = self.run_preset(self.fake_media_launcher(), 'split',
|
||||||
|
'https://example.org/video')
|
||||||
|
self.assertNotEqual(result.returncode, 0)
|
||||||
|
self.assertFalse(list((self.media / 'output').iterdir()))
|
||||||
|
|
||||||
def test_symlinked_input_is_rejected(self):
|
def test_symlinked_input_is_rejected(self):
|
||||||
(self.media / 'input').rmdir()
|
(self.media / 'input').rmdir()
|
||||||
(self.media / 'input').symlink_to(self.root)
|
(self.media / 'input').symlink_to(self.root)
|
||||||
|
|||||||
93
ansible/roles/desktop_ai_media/tests/test_preset_rvc.py
Normal file
93
ansible/roles/desktop_ai_media/tests/test_preset_rvc.py
Normal file
@@ -0,0 +1,93 @@
|
|||||||
|
import importlib.util
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
from types import ModuleType
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import Mock, patch
|
||||||
|
|
||||||
|
|
||||||
|
class SeparationWorkerTest(unittest.TestCase):
|
||||||
|
def test_convert_only_applies_mia_voce_without_importing_separator(self):
|
||||||
|
spec = importlib.util.spec_from_file_location(
|
||||||
|
'preset_rvc', Path(__file__).resolve().parents[1] / 'files/preset_rvc.py')
|
||||||
|
worker = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(worker)
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
root = Path(directory)
|
||||||
|
output = root / 'output'
|
||||||
|
job = output / 'job'
|
||||||
|
job.mkdir(parents=True)
|
||||||
|
source = job / 'audio.wav'
|
||||||
|
source.write_bytes(b'audio')
|
||||||
|
weights = root / 'state/weights/mia_voce.pth'
|
||||||
|
index = root / 'state/mia_voce/added_IVF256_Flat_nprobe_1_mia_voce_v2.index'
|
||||||
|
for path in (weights, index):
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
path.write_bytes(b'model')
|
||||||
|
|
||||||
|
def mapped_path(value):
|
||||||
|
return root / str(value).removeprefix('/work/') if str(value).startswith(
|
||||||
|
'/work/') else Path(value)
|
||||||
|
|
||||||
|
config = ModuleType('configs.config')
|
||||||
|
config.Config = Mock()
|
||||||
|
vc = ModuleType('infer.vc.modules')
|
||||||
|
voice = Mock()
|
||||||
|
voice.vc_single.return_value = ('Success', (40000, [0.1, 0.2]))
|
||||||
|
vc.VC = Mock(return_value=voice)
|
||||||
|
sf = ModuleType('soundfile')
|
||||||
|
sf.write = Mock(side_effect=lambda path, data, rate: path.write_bytes(b'converted'))
|
||||||
|
modules = {'configs.config': config, 'infer.vc.modules': vc,
|
||||||
|
'soundfile': sf, 'tools.pymss_webui': None}
|
||||||
|
with patch.object(worker, 'Path', mapped_path), \
|
||||||
|
patch.object(sys, 'argv', ['preset_rvc.py', str(source), str(job),
|
||||||
|
'--convert-only']), \
|
||||||
|
patch.dict(sys.modules, modules), patch.dict(os.environ):
|
||||||
|
worker.main()
|
||||||
|
voice.get_vc.assert_called_once_with('mia_voce.pth')
|
||||||
|
self.assertEqual(voice.vc_single.call_args.args[1], str(source))
|
||||||
|
self.assertEqual(voice.vc_single.call_args.args[4], str(index))
|
||||||
|
self.assertEqual((job / 'vocals-mia_voce.wav').read_bytes(), b'converted')
|
||||||
|
self.assertFalse((job / 'vocals').exists())
|
||||||
|
self.assertFalse((job / 'instrumental').exists())
|
||||||
|
|
||||||
|
def test_separate_only_does_not_require_personal_voice_weights(self):
|
||||||
|
spec = importlib.util.spec_from_file_location(
|
||||||
|
'preset_rvc', Path(__file__).resolve().parents[1] / 'files/preset_rvc.py')
|
||||||
|
worker = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(worker)
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
output = Path(directory)
|
||||||
|
job = output / 'job'
|
||||||
|
job.mkdir()
|
||||||
|
source = job / 'audio.wav'
|
||||||
|
source.write_bytes(b'fixture')
|
||||||
|
separator = ModuleType('tools.pymss_webui')
|
||||||
|
|
||||||
|
def separate(model, audio, vocals, unused, instrumental, fmt, **kwargs):
|
||||||
|
self.assertEqual(model, 'vocals-bs-roformer-368')
|
||||||
|
self.assertEqual(audio, str(source))
|
||||||
|
(Path(vocals) / 'stem.wav').write_bytes(b'vocals')
|
||||||
|
(Path(instrumental) / 'stem.wav').write_bytes(b'instrumental')
|
||||||
|
yield 'Separated'
|
||||||
|
|
||||||
|
separator.pymss_separate = separate
|
||||||
|
|
||||||
|
def mapped_path(value):
|
||||||
|
return output if str(value) == '/work/output' else Path(value)
|
||||||
|
|
||||||
|
with patch.object(worker, 'Path', mapped_path), \
|
||||||
|
patch.object(sys, 'argv', ['preset_rvc.py', str(source), str(job),
|
||||||
|
'--separate-only']), \
|
||||||
|
patch.dict(sys.modules, {'tools.pymss_webui': separator}), \
|
||||||
|
patch.dict(os.environ):
|
||||||
|
worker.main()
|
||||||
|
self.assertTrue((job / 'vocals/stem.wav').is_file())
|
||||||
|
self.assertTrue((job / 'instrumental/stem.wav').is_file())
|
||||||
|
self.assertFalse((job / 'vocals-mia_voce.wav').exists())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
142
docs/ai-media-presets.md
Normal file
142
docs/ai-media-presets.md
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
# Preset offline `ai-media`
|
||||||
|
|
||||||
|
Tutti i preset video accettano un nome MP4 locale oppure un URL HTTP(S).
|
||||||
|
I file locali vanno in `~/.local/share/ai-media/input/`. I preset avviano un servizio
|
||||||
|
`systemd --user` e tornano subito; FaceFusion e RVC restano nei container
|
||||||
|
offline. Il terminale stampa il nome del job e il comando per seguirne i log.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Estrae l'audio, separa voce/strumentale, converte tutta la traccia
|
||||||
|
# vocale con mia_voce e restituisce solo l'audio finale mixato.
|
||||||
|
ai-media preset audio-convert video1.mp4
|
||||||
|
|
||||||
|
# 2. Applica source11.jpg ... source18.jpg al video: conserva l'audio
|
||||||
|
# originale se presente, altrimenti produce un video senza audio.
|
||||||
|
ai-media preset video-convert video1.mp4
|
||||||
|
|
||||||
|
# 3. Unisce un video in input/ con un audio presente in input/ oppure output/.
|
||||||
|
ai-media preset merge video1.mp4 audio.wav
|
||||||
|
|
||||||
|
# 4. Esegue voce e volti, poi unisce il video modificato con l'audio convertito.
|
||||||
|
# Se l'input è un URL, scarica prima un singolo video con yt-dlp.
|
||||||
|
ai-media preset convert 'https://esempio.org/video'
|
||||||
|
|
||||||
|
# 5. Separa il video (senza ricodificarlo) dalla prima traccia audio.
|
||||||
|
ai-media preset split video1.mp4
|
||||||
|
|
||||||
|
# 6. Come split, poi separa l'audio in voce e strumentale, senza convertirne la voce.
|
||||||
|
ai-media preset split-stems video1.mp4
|
||||||
|
|
||||||
|
# 7. Sovrappone voce e strumentale in un unico audio (non concatena le tracce).
|
||||||
|
ai-media preset mix vocals.wav instrumental.wav
|
||||||
|
|
||||||
|
# 8. Applica mia_voce direttamente a un audio, senza separazione né remix.
|
||||||
|
ai-media preset voice-convert voce.wav
|
||||||
|
```
|
||||||
|
|
||||||
|
## Applicare mia_voce a un audio
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ai-media preset voice-convert voce.wav
|
||||||
|
ai-media preset voice-convert video1-split-stems/vocals.wav --output video1-mia_voce.wav
|
||||||
|
```
|
||||||
|
|
||||||
|
`voice-convert` legge un audio locale in `input/` oppure `output/`, anche in
|
||||||
|
una sottocartella, e produce `output/<nome-audio>-mia_voce.wav`. `--output`
|
||||||
|
permette di scegliere un altro nome WAV. Converte prima la traccia in WAV e
|
||||||
|
applica direttamente il modello RVC `mia_voce` con il relativo indice e RMVPE,
|
||||||
|
senza BS Roformer e senza aggiungere lo strumentale. Usare preferibilmente
|
||||||
|
una voce isolata: il preset non rimuove musica né separa parlanti.
|
||||||
|
Accetta i formati audio decodificabili dal FFmpeg installato. Richiede il
|
||||||
|
modello e l'indice personali già presenti nello stato RVC, funziona offline
|
||||||
|
in background, conserva l'originale e rifiuta risultati già esistenti.
|
||||||
|
Gli intermedi restano nella sottocartella nascosta del job in `output/`.
|
||||||
|
|
||||||
|
Per rimettere lo strumentale dopo la conversione:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ai-media preset mix video1-mia_voce.wav video1-split-stems/instrumental.wav --output video1-mix.wav
|
||||||
|
```
|
||||||
|
|
||||||
|
## Unire voce e strumentale
|
||||||
|
|
||||||
|
`mix` usa due audio locali in `input/` o `output/`, anche nelle sottocartelle
|
||||||
|
create da `split-stems`:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ai-media preset mix video1-split-stems/vocals.wav video1-split-stems/instrumental.wav --output video1-mix.wav
|
||||||
|
```
|
||||||
|
|
||||||
|
Il risultato è `output/video1-mix.wav`, PCM WAV a 16 bit. Senza `--output`,
|
||||||
|
il nome è `<nome-vocale>-mix.wav` (per esempio `vocals-mix.wav`). Le tracce
|
||||||
|
partono insieme da zero e vengono sommate a volume originale, senza
|
||||||
|
normalizzazione; la durata è quella della traccia più lunga. Livelli troppo
|
||||||
|
alti possono causare clipping. Il preset non esegue separazione o conversione
|
||||||
|
vocale, non modifica gli originali e non sovrascrive file esistenti. Parte in
|
||||||
|
background come gli altri preset e usa solo FFmpeg nel container offline.
|
||||||
|
Gli audio devono essere univoci tra `input/` e `output/`; percorsi assoluti,
|
||||||
|
`..`, link simbolici e URL audio non sono accettati.
|
||||||
|
|
||||||
|
## Video da URL
|
||||||
|
|
||||||
|
Per ogni preset video si può sostituire il nome del video con un URL tra virgolette:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ai-media preset split 'https://esempio.org/video'
|
||||||
|
ai-media preset split-stems 'https://esempio.org/video'
|
||||||
|
ai-media preset audio-convert 'https://esempio.org/video'
|
||||||
|
ai-media preset video-convert 'https://esempio.org/video'
|
||||||
|
ai-media preset merge 'https://esempio.org/video' audio.wav
|
||||||
|
ai-media preset convert 'https://esempio.org/video'
|
||||||
|
# Anche convert accetta un file locale, senza download:
|
||||||
|
ai-media preset convert video1.mp4
|
||||||
|
```
|
||||||
|
|
||||||
|
Il download con `yt-dlp` avviene una sola volta nello stesso job in background,
|
||||||
|
prima dell'elaborazione. Il video scaricato resta in `input/download-<ID>.mp4`;
|
||||||
|
i risultati usano lo stesso prefisso `download-<ID>` al posto di `video1`.
|
||||||
|
Serve `yt-dlp` sull'host solo per gli URL. L'audio di `merge` rimane un file
|
||||||
|
locale in `input/` oppure `output/`. URL locali/privati o contenenti credenziali
|
||||||
|
non vengono accettati. Se il download fallisce, l'elaborazione non parte.
|
||||||
|
|
||||||
|
`split` produce `output/video1-split/video.mp4` (muto) e `audio.wav`.
|
||||||
|
`split-stems` produce `output/video1-split-stems/` con `video.mp4`, `audio.wav`,
|
||||||
|
`vocals.wav` e `instrumental.wav`. L'audio estratto è PCM WAV a 16 bit;
|
||||||
|
la separazione usa BS Roformer offline nel container RVC e non richiede
|
||||||
|
il modello personale `mia_voce`. Entrambi richiedono un video con audio,
|
||||||
|
non modificano l'originale e rifiutano una cartella risultato già esistente.
|
||||||
|
Mantengono gli intermedi nella sottocartella nascosta del job in `output/`;
|
||||||
|
i risultati pubblicati sono hard link e non duplicano lo spazio dei file.
|
||||||
|
|
||||||
|
`video-convert` e il passaggio video di `convert` usano lo stesso profilo
|
||||||
|
FaceFusion: HyperSwap 1a 256 (pixel boost 256x256, peso 0.5), rilevatore
|
||||||
|
`yolo_face` 640x640 agli angoli 0/90/180/270, selezione `one` per volto
|
||||||
|
grande, filtri `female` e `white`, maschere `occlusion region area box` con
|
||||||
|
`xseg_1` e `bisenet_resnet_34` (blur 0.3), H.264 `libx264` veryfast, qualità
|
||||||
|
80 e 30 fps. L'audio originale viene ripristinato separatamente quando esiste.
|
||||||
|
|
||||||
|
Risultati: `output/video1-mia_voce.wav`, `output/video1-facefusion.mp4` e
|
||||||
|
`output/video1-unito.mp4`. Il preset `convert` crea
|
||||||
|
`output/video1-completo.mp4` (o `output/download-<ID>-completo.mp4` da URL),
|
||||||
|
mantenendo anche l'audio e il video intermedi. Richiede `source11.jpg`–`source18.jpg`
|
||||||
|
in `input/` e un video che contenga audio. **Solo il download** tramite
|
||||||
|
`yt-dlp` usa la rete; non usa la configurazione o i cookie personali di
|
||||||
|
`yt-dlp` e non scarica playlist. I file esistenti non vengono sovrascritti. Il
|
||||||
|
primo e il secondo preset conservano i passaggi intermedi in una sottocartella
|
||||||
|
`.video1-...` di `output/`, utile per diagnosi e recupero; non viene rimossa
|
||||||
|
automaticamente.
|
||||||
|
|
||||||
|
Per controllare un job, usare il nome stampato dal comando:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
journalctl --user -fu ai-media-preset-YYYYMMDD-HHMMSS-ID
|
||||||
|
systemctl --user status ai-media-preset-YYYYMMDD-HHMMSS-ID
|
||||||
|
```
|
||||||
|
|
||||||
|
Il preset `audio-convert` converte l'intero stem vocale: non distingue automaticamente
|
||||||
|
voci maschili e femminili e non separa parlanti sovrapposti. L'elaborazione è
|
||||||
|
in background, **non** più rapida della capacità della CPU. I nomi dei video locali
|
||||||
|
devono essere semplici, senza percorsi; gli audio possono indicare sottocartelle
|
||||||
|
relative a `input/` o `output/`. Se lo stesso audio
|
||||||
|
è in `input/` e `output/`, il comando rifiuta l'ambiguità. Tutti i video di
|
||||||
|
input dei preset devono essere MP4 con un nome diverso dal risultato atteso.
|
||||||
Reference in New Issue
Block a user