Add local AI media tools for Fedora desktop

This commit is contained in:
Fabio Scotto di Santolo
2026-10-25 16:42:58 +01:00
parent 479b60f270
commit 7b6d5396ab
16 changed files with 1182 additions and 1 deletions

View File

@@ -0,0 +1,45 @@
import configparser
import pathlib
import re
import sys
import xml.etree.ElementTree as ET
root = pathlib.Path(sys.argv[1]).resolve()
home = pathlib.Path.home()
local_filesystems = {
"btrfs", "ext2", "ext3", "ext4", "xfs", "zfs", "tmpfs", "overlay",
"ramfs", "ntfs3", "vfat", "exfat",
}
mounts = []
for line in pathlib.Path("/proc/self/mountinfo").read_text().splitlines():
fields, description = line.split(" - ", 1)
mount = re.sub(r"\\([0-7]{3})", lambda m: chr(int(m[1], 8)), fields.split()[4])
mounts.append((pathlib.Path(mount), description.split()[0]))
covering = [(p, kind) for p, kind in mounts if root == p or root.is_relative_to(p)]
if covering:
selected = max(covering, key=lambda entry: len(entry[0].parts))
if selected[1] not in local_filesystems:
raise SystemExit("Media storage is not on a local filesystem; refusing to start")
for mount, kind in mounts:
if mount.is_relative_to(root) and kind not in local_filesystems:
raise SystemExit("Non-local mount beneath media storage; refusing to start")
sync_roots = []
nextcloud = home / ".config/Nextcloud/nextcloud.cfg"
if nextcloud.exists():
configuration = configparser.ConfigParser(interpolation=None, strict=False)
configuration.read(nextcloud)
for section in configuration.sections():
for key, value in configuration.items(section):
if key.lower().endswith("localpath"):
sync_roots.append(pathlib.Path(value).expanduser().resolve())
for configuration in (
home / ".config/syncthing/config.xml",
home / ".local/state/syncthing/config.xml",
):
if configuration.exists():
for folder in ET.parse(configuration).getroot().findall("folder"):
if folder.get("path"):
sync_roots.append(pathlib.Path(folder.get("path")).expanduser().resolve())
for path in sync_roots:
if root == path or root.is_relative_to(path) or path.is_relative_to(root):
raise SystemExit("Media storage overlaps a Nextcloud/Syncthing folder; refusing to start")

View File

@@ -0,0 +1,88 @@
import hashlib
import pathlib
import sys
import zipfile
app = sys.argv[1]
root = pathlib.Path("/opt/app")
if app == "facefusion":
sys.path.insert(0, str(root))
from facefusion import state_manager
from facefusion.args import apply_args
from facefusion.program import create_program
from facefusion.core import common_pre_check, processors_pre_check
args = vars(create_program().parse_args([
"run", "--execution-providers", "cpu",
"--processors", "face_swapper",
]))
apply_args(args, state_manager.init_item)
if not common_pre_check() or not processors_pre_check():
raise RuntimeError("FaceFusion model preparation failed")
else:
for relative in (
"hubert_base/config.json",
"hubert_base/preprocessor_config.json",
"hubert_base/pytorch_model.bin",
"rmvpe.pt",
):
destination = root / "assets" / relative
if relative == "rmvpe.pt":
destination = root / "assets/rmvpe/rmvpe.pt"
destination.parent.mkdir(parents=True, exist_ok=True)
if not destination.is_file():
raise FileNotFoundError("Missing checksum-pinned public model: " + str(destination))
for directory in ("weights", "indices", "pretrained", "pretrained_v2", "pymss_weights"):
(root / "assets" / directory).mkdir(parents=True, exist_ok=True)
# Mutable working data stays outside the immutable application tree.
for name, destination in (
("TEMP", "/tmp/rvc-temp"),
("assets/weights", "/work/state/weights"),
("logs", "/work/state"),
):
path = root / name
if path.exists():
import shutil
shutil.rmtree(path)
path.symlink_to(destination)
# Expose only separation models that are actually baked into this image.
separation = root / "tools/pymss_webui.py"
original = "PYMSS_MODEL_CHOICES = [spec.label for spec in MODEL_SPECS]"
replacement = """PYMSS_MODEL_CHOICES = [
spec.label for spec in MODEL_SPECS
if (weight_pymss_root / spec.model_file).is_file()
and (weight_pymss_root / spec.config_file).is_file()
]"""
code = separation.read_text()
if code.count(original) != 1:
raise RuntimeError("Pinned RVC separation model selector has changed")
separation.write_text(code.replace(original, replacement))
webui = root / "webui.py"
code = webui.read_text()
for label, destination in (
("主结果文件夹", "/work/output/vocals"),
("分离残余文件夹", "/work/output/instrumental"),
):
original = 'label=i18n("' + label + '"), value="opt"'
if code.count(original) != 1:
raise RuntimeError("Pinned RVC separation output selector has changed")
code = code.replace(original, 'label=i18n("' + label + '"), value="' + destination + '"')
webui.write_text(code)
# Bake only the public silence fixture; personal datasets never enter the build.
with zipfile.ZipFile(root / "assets/mute.zip") as archive:
destination = pathlib.Path("/opt/training-fixture")
for entry in archive.infolist():
target = (destination / entry.filename).resolve()
if not target.is_relative_to(destination):
raise ValueError("Invalid public silence archive member")
archive.extractall(destination)
with open("/opt/model-checksums.sha256", "w") as manifest:
for directory in (root / ".assets", root / "assets"):
if directory.exists():
for path in sorted(directory.rglob("*")):
if path.is_file():
digest = hashlib.file_digest(path.open("rb"), "sha256").hexdigest()
manifest.write(digest + " " + str(path) + "\n")

View File

@@ -0,0 +1,63 @@
--index-url https://pypi.org/simple
aiofiles==24.1.0
annotated-doc==0.0.5
annotated-types==0.8.0
anyio==4.15.1
brotli==1.2.0
certifi==2026.7.22
click==8.5.0
fastapi==0.143.0
ffmpy==1.0.0
filelock==4.1.1
flatbuffers==25.12.19
fsspec==2026.9.0
gradio==5.50.0
gradio_client==1.14.0
gradio_rangeslider==0.0.8
groovy==0.1.2
h11==0.16.0
hf-xet==1.7.0
httpcore==1.0.9
httpx==0.28.1
huggingface_hub==1.33.0
idna==3.20
Jinja2==3.1.6
markdown-it-py==4.2.0
MarkupSafe==3.0.4
mdurl==0.1.2
ml_dtypes==0.6.0
numpy==2.4.6
onnx==1.23.1
onnxruntime==1.30.0
opencv-python-headless==5.0.0.93
opentelemetry-api==1.45.1
orjson==3.13.0
packaging==26.3
pandas==2.3.3
pillow==11.3.0
pip==25.0.1
protobuf==7.36.2
pydantic==2.12.3
pydantic_core==2.41.4
pydub==0.25.1
Pygments==2.21.0
python-dateutil==2.9.0.post0
python-multipart==0.0.32
pytz==2026.5
PyYAML==6.0.3
rich==15.0.0
ruff==0.17.0
safehttpx==0.1.7
scipy==1.18.1
semantic-version==2.10.0
shellingham==1.5.4
six==1.17.0
starlette==0.52.1
tomlkit==0.13.3
tqdm==4.70.1
typer==0.27.3
typing-inspection==0.4.4
typing_extensions==4.16.0
tzdata==2026.5
uvicorn==0.54.0
websockets==15.0.1

View File

@@ -0,0 +1,120 @@
--index-url https://pypi.org/simple
--extra-index-url https://download.pytorch.org/whl/cpu
absl-py==2.5.1
aiohappyeyeballs==2.7.1
aiohttp==3.14.5
aiosignal==1.4.0
altair==4.2.2
anyio==3.7.1
attrs==26.1.0
audioread==3.1.0
av==15.1.0
certifi==2026.7.22
cffi==2.1.1
charset-normalizer==3.5.2
click==8.5.0
cloudpickle==3.1.2
coloredlogs==15.0.1
contourpy==1.3.3
cycler==0.12.1
decorator==5.3.1
einops==0.8.2
entrypoints==0.4
faiss-cpu==1.15.1
fastapi==0.99.1
ffmpeg-python==0.2.0
ffmpy==1.0.0
filelock==4.1.1
flatbuffers==25.12.19
fonttools==4.66.1
FreeSimpleGUI==5.1.1
frozenlist==1.8.0
fsspec==2026.9.0
future==1.0.0
gradio==3.14.0
grpcio==1.84.0
h11==0.14.0
hf-xet==1.7.0
httpcore==0.16.3
httpx==0.23.3
huggingface_hub==0.36.2
humanfriendly==10.0
hyper-connections==0.4.2
idna==3.20
Jinja2==3.1.6
joblib==1.6.0
jsonschema==4.26.0
jsonschema-specifications==2025.9.1
kiwisolver==1.5.1
lazy-loader==0.6
librosa==0.10.2.post1
linkify-it-py==2.2.0
llvmlite==0.50.0
local-attention==1.11.2
Markdown==3.11
markdown-it-py==2.2.0
MarkupSafe==3.0.4
matplotlib==3.11.2
mdit-py-plugins==0.3.5
mdurl==0.1.2
mpmath==1.3.0
msgpack==1.2.3
multidict==7.1.0
narwhals==2.27.1
networkx==3.7
numba==0.68.0
numpy==1.26.4
onnxruntime==1.31.0
opencv-python-headless==4.11.0.86
orjson==3.13.0
packaging==26.3
pandas==3.0.6
pillow==12.3.0
pip==25.0.1
platformdirs==4.13.0
pooch==1.9.0
praat-parselmouth==0.4.7
propcache==0.5.4
protobuf==7.36.2
pycparser==3.11
pycryptodome==3.24.1
pydantic==1.10.26
pydub==0.25.1
pyparsing==3.0.9
python-dateutil==2.9.0.post0
python-multipart==0.0.32
PyYAML==6.0.3
referencing==0.37.0
regex==2026.9.29
requests==2.34.2
rfc3986==1.5.0
rpds-py==2026.9.1
safetensors==0.8.0
scikit-learn==1.9.1
scipy==1.17.1
setuptools==80.10.2
six==1.17.0
sniffio==1.3.1
sounddevice==0.5.6
soundfile==0.14.0
soxr==1.1.0
starlette==0.27.0
sympy==1.14.0
tensorboard==2.21.0
tensorboard-data-server==0.7.2
threadpoolctl==3.7.0
tokenizers==0.21.4
toolz==1.2.0
torch==2.4.1+cpu
torchaudio==2.4.1+cpu
torchfcpe==0.0.4
torchvision==0.19.1+cpu
tqdm==4.70.1
transformers==4.49.0
typing_extensions==4.16.0
urllib3==2.8.0
uvicorn==0.22.0
websockets==10.4
Werkzeug==3.1.9
wheel==0.48.0
yarl==1.25.1

View File

@@ -0,0 +1,111 @@
import os
import pathlib
import signal
import shutil
import subprocess
import sys
import time
import urllib.request
app = os.environ["APP"]
os.chdir("/opt/app")
if sys.argv[1:] == ["verify"]:
os.execv(sys.executable, [sys.executable, "/opt/verify.py"])
if sys.argv[1:2] == ["ffmpeg"]:
os.execv("/usr/bin/ffmpeg", ["ffmpeg", *sys.argv[2:]])
if sys.argv[1:2] == ["cli"]:
if app != "facefusion":
raise SystemExit("CLI is available for FaceFusion only")
os.execv(sys.executable, [sys.executable, "facefusion.py", *sys.argv[2:]])
if app == "facefusion":
command = [
sys.executable, "facefusion.py", "run",
"--execution-providers", "cpu", "--processors", "face_swapper",
"--temp-path", "/work/state/tmp", "--jobs-path", "/work/state",
"--output-path", "/work/output",
]
port = 7860
else:
pathlib.Path("/tmp/rvc-temp").mkdir(exist_ok=True)
weights = pathlib.Path("/work/state/weights")
weights.mkdir(exist_ok=True)
for source in pathlib.Path("/work/models/weights").glob("*.pth"):
target = weights / source.name
if not target.exists() and not target.is_symlink():
target.symlink_to(source)
fixture = pathlib.Path("/opt/training-fixture/mute")
for source in fixture.rglob("*"):
target = pathlib.Path("/work/state/mute") / source.relative_to(fixture)
if source.is_dir():
target.mkdir(parents=True, exist_ok=True)
elif not target.exists():
shutil.copyfile(source, target)
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",
)
command = [sys.executable, "webui.py", "--noautoopen", "--port", "7865"]
port = 7865
server = subprocess.Popen(command)
browser = None
profile = pathlib.Path("/tmp/browser")
profile.mkdir(exist_ok=True)
(profile / "user.js").write_text('''
user_pref("browser.download.folderList", 2);
user_pref("browser.download.dir", "/work/output");
user_pref("browser.download.useDownloadDir", true);
user_pref("widget.use-xdg-desktop-portal.file-picker", 0);
user_pref("browser.shell.checkDefaultBrowser", false);
user_pref("browser.aboutwelcome.enabled", false);
user_pref("datareporting.policy.dataSubmissionEnabled", false);
user_pref("toolkit.telemetry.enabled", false);
''')
bookmarks = pathlib.Path.home() / ".config/gtk-3.0/bookmarks"
bookmarks.parent.mkdir(parents=True, exist_ok=True)
bookmarks.write_text("file:///work/input Input\nfile:///work/output Output\nfile:///work/models Models\n")
def stop(*_):
if browser is not None and browser.poll() is None:
browser.terminate()
if server.poll() is None:
server.terminate()
signal.signal(signal.SIGTERM, stop)
signal.signal(signal.SIGINT, stop)
try:
url = f"http://127.0.0.1:{port}"
for _ in range(180):
if server.poll() is not None:
raise RuntimeError(f"{app} exited: {server.returncode}")
try:
with urllib.request.urlopen(url, timeout=1) as response:
if response.status == 200:
break
except OSError:
time.sleep(1)
else:
raise RuntimeError("Offline WebUI did not become ready")
print(f"{app}: offline WebUI ready", flush=True)
if sys.argv[1:] == ["smoke"]:
subprocess.run([
"firefox-esr", "--headless", "--no-remote", "--profile", "/tmp/browser",
"--screenshot", "/tmp/offline-ui.png", url,
], check=True, timeout=90)
assert pathlib.Path("/tmp/offline-ui.png").stat().st_size > 1000
raise SystemExit(0)
browser = subprocess.Popen([
"firefox-esr", "--no-remote", "--profile", "/tmp/browser", url,
])
while browser.poll() is None:
if server.poll() is not None:
raise RuntimeError("WebUI terminated unexpectedly")
time.sleep(1)
finally:
stop()
if browser is not None:
browser.wait(timeout=15)
server.wait(timeout=15)

View File

@@ -0,0 +1,139 @@
import os
import gc
import pathlib
import socket
import subprocess
import sys
import tempfile
interfaces = {p.name for p in pathlib.Path("/sys/class/net").iterdir()}
assert interfaces == {"lo"}, interfaces
for family, address in (
(socket.AF_INET, ("1.1.1.1", 443)),
(socket.AF_INET6, ("2606:4700:4700::1111", 443, 0, 0)),
):
with socket.socket(family, socket.SOCK_STREAM) as connection:
connection.settimeout(2)
try:
connection.connect(address)
except OSError:
pass
else:
raise RuntimeError("External networking is available")
subprocess.run(["sha256sum", "--quiet", "--check", "/opt/model-checksums.sha256"], check=True)
if os.environ["APP"] == "facefusion":
sys.path.insert(0, "/opt/app")
from facefusion import state_manager
from facefusion.args import apply_args
from facefusion.program import create_program
from facefusion.core import common_pre_check, processors_pre_check
args = vars(create_program().parse_args([
"run", "--execution-providers", "cpu", "--processors", "face_swapper",
]))
apply_args(args, state_manager.init_item)
assert common_pre_check() and processors_pre_check()
import numpy as np
import onnxruntime as ort
options = ort.SessionOptions()
options.intra_op_num_threads = 4
options.inter_op_num_threads = 1
model = ort.InferenceSession(
"/opt/app/.assets/models/hyperswap_1a_256.onnx",
sess_options=options, providers=["CPUExecutionProvider"],
)
feeds = {}
for argument in model.get_inputs():
assert argument.type == "tensor(float)"
shape = [size if isinstance(size, int) and size > 0 else 1 for size in argument.shape]
feeds[argument.name] = np.full(shape, 0.01, dtype=np.float32)
assert all(np.isfinite(result).all() for result in model.run(None, feeds))
else:
sys.path.insert(0, "/opt/app")
import numpy as np
import torch
import transformers
import onnxruntime
assert not torch.cuda.is_available()
torch.set_num_threads(4)
from infer.hubert import load_hubert_model, extract_hubert_features
from infer.rmvpe import RMVPE
with torch.inference_mode():
hubert = load_hubert_model("cpu", False)
features = extract_hubert_features(hubert, torch.zeros(1, 16000), "v2")
assert torch.isfinite(features).all()
del hubert, features
pitch = RMVPE("/opt/app/assets/rmvpe/rmvpe.pt", False, "cpu")
result = pitch.infer_from_audio(np.zeros(16000, dtype=np.float32))
assert len(result) > 0 and np.isfinite(result).all()
del pitch
gc.collect()
# Exercise the exact WebUI subprocess entrypoint, not only in-process imports.
from scipy.io import wavfile
with tempfile.TemporaryDirectory(prefix="rvc-slicing-") as temporary:
directory = pathlib.Path(temporary)
dataset = directory / "input"
experiment = directory / "experiment"
dataset.mkdir()
experiment.mkdir()
samples = np.arange(4 * 40000, dtype=np.float32) / 40000
waveform = (0.2 * np.sin(2 * np.pi * 220 * samples)).astype(np.float32)
wavfile.write(dataset / "synthetic.wav", 40000, waveform)
subprocess.run([
sys.executable, "train/preprocess.py", str(dataset), "40000", "1",
str(experiment), "False", "3.7",
], check=True, timeout=120)
assert list((experiment / "0_gt_wavs").glob("*.wav"))
assert list((experiment / "1_16k_wavs").glob("*.wav"))
print("rvc: synthetic data slicing subprocess verified", flush=True)
# Check the v2/40k training baseline and writable inference-model export.
from train.utils import get_hparams_from_file
from train.process_ckpt import savee
hps = get_hparams_from_file("configs/v1/40k.json")
checkpoint = torch.load("assets/pretrained_v2/f0G40k.pth", map_location="cpu")
assert checkpoint["model"]
pathlib.Path("/work/state/weights").mkdir(exist_ok=True)
savee(checkpoint["model"], "40k", 1, "offline-readiness", 0, "v2", hps)
exported = pathlib.Path("assets/weights/offline-readiness.pth")
assert exported.is_file()
exported.unlink()
del checkpoint
checkpoint = torch.load("assets/pretrained_v2/f0D40k.pth", map_location="cpu")
assert checkpoint["model"]
del checkpoint
assert pathlib.Path("/opt/training-fixture/mute/0_gt_wavs/mute40k.wav").is_file()
print("rvc: v2/40k training assets and model export verified", flush=True)
# Exercise the WebUI's real worker and encoder on a synthetic stereo mix.
with tempfile.TemporaryDirectory(prefix="rvc-separation-") as temporary:
directory = pathlib.Path(temporary)
sample_rate = 44100
time_axis = np.arange(2 * sample_rate, dtype=np.float32) / sample_rate
left = 0.1 * np.sin(2 * np.pi * 220 * time_axis)
right = 0.1 * np.sin(2 * np.pi * 330 * time_axis)
mix = np.stack((left, right), axis=1).astype(np.float32)
wavfile.write(directory / "synthetic.wav", sample_rate, mix)
subprocess.run([
sys.executable, "-c",
"import sys; from pathlib import Path; p=Path(sys.argv[1]); sys.argv=sys.argv[:1]; "
"from tools.pymss_webui import pymss_separate, resolve_model, PYMSS_MODEL_CHOICES; "
"assert PYMSS_MODEL_CHOICES == [resolve_model('vocals-bs-roformer-368').label]; "
"list(pymss_separate('vocals-bs-roformer-368', str(p/'synthetic.wav'), "
"str(p/'vocals'), None, str(p/'instrumental'), 'wav'))",
str(directory),
], check=True, timeout=600, env={
**os.environ, "OMP_NUM_THREADS": "4", "MKL_NUM_THREADS": "4",
})
import soundfile as sf
stems = []
for name in ("vocals", "instrumental"):
files = list((directory / name).glob("*.wav"))
assert len(files) == 1, (name, files)
data, rate = sf.read(files[0], dtype="float32", always_2d=True)
assert rate == sample_rate and data.shape == mix.shape
assert np.isfinite(data).all()
stems.append(data)
assert np.allclose(stems[0] + stems[1], mix, atol=1e-4)
print("rvc: offline stereo vocal/instrumental separation verified", flush=True)
gc.collect()
subprocess.run([sys.executable, "/opt/session.py", "smoke"], check=True)
print(os.environ["APP"] + ": models verified, offline UI ready, IPv4/IPv6 egress blocked")