From 7b6d5396ab1af60f5c4e00222a74bc23b8d556ab Mon Sep 17 00:00:00 2001 From: Fabio Scotto di Santolo Date: Sun, 25 Oct 2026 16:42:58 +0100 Subject: [PATCH] Add local AI media tools for Fedora desktop --- ansible/inventory/host_vars/ikaros.yml | 4 +- .../roles/desktop_ai_media/defaults/main.yml | 10 + .../desktop_ai_media/files/check_storage.py | 45 ++++ .../roles/desktop_ai_media/files/prepare.py | 88 +++++++ .../files/requirements-facefusion.lock | 63 +++++ .../files/requirements-rvc.lock | 120 ++++++++++ .../roles/desktop_ai_media/files/session.py | 111 +++++++++ .../roles/desktop_ai_media/files/verify.py | 139 +++++++++++ ansible/roles/desktop_ai_media/tasks/main.yml | 217 ++++++++++++++++++ .../templates/Containerfile.j2 | 40 ++++ .../desktop_ai_media/templates/ai-media.j2 | 79 +++++++ .../templates/application.desktop.j2 | 7 + .../templates/containerignore.j2 | 15 ++ .../desktop_ai_media/tests/test_launcher.py | 108 +++++++++ .../roles/desktop_ai_media/vars/models.yml | 134 +++++++++++ ansible/site.yml | 3 + 16 files changed, 1182 insertions(+), 1 deletion(-) create mode 100644 ansible/roles/desktop_ai_media/defaults/main.yml create mode 100644 ansible/roles/desktop_ai_media/files/check_storage.py create mode 100644 ansible/roles/desktop_ai_media/files/prepare.py create mode 100644 ansible/roles/desktop_ai_media/files/requirements-facefusion.lock create mode 100644 ansible/roles/desktop_ai_media/files/requirements-rvc.lock create mode 100644 ansible/roles/desktop_ai_media/files/session.py create mode 100644 ansible/roles/desktop_ai_media/files/verify.py create mode 100644 ansible/roles/desktop_ai_media/tasks/main.yml create mode 100644 ansible/roles/desktop_ai_media/templates/Containerfile.j2 create mode 100644 ansible/roles/desktop_ai_media/templates/ai-media.j2 create mode 100644 ansible/roles/desktop_ai_media/templates/application.desktop.j2 create mode 100644 ansible/roles/desktop_ai_media/templates/containerignore.j2 create mode 100644 ansible/roles/desktop_ai_media/tests/test_launcher.py create mode 100644 ansible/roles/desktop_ai_media/vars/models.yml diff --git a/ansible/inventory/host_vars/ikaros.yml b/ansible/inventory/host_vars/ikaros.yml index 5b74d95..14a9e36 100644 --- a/ansible/inventory/host_vars/ikaros.yml +++ b/ansible/inventory/host_vars/ikaros.yml @@ -3,8 +3,10 @@ hostname: ikaros codex_relay_install_enabled: true chatgpt_desktop_enabled: true +desktop_ai_media_enabled: true host_packages: + - podman - openssh-clients - openssh-server - mesa-vulkan-drivers @@ -232,7 +234,7 @@ gnome_gsettings_settings: - schema: org.gnome.shell key: app-picker-layout value: >- - [{'System': <{'position': <0>}>, 'Utilities': <{'position': <1>}>, 'org.fedoraproject.MediaWriter.desktop': <{'position': <2>}>, 'org.gnome.Contacts.desktop': <{'position': <3>}>, 'org.gnome.Calendar.desktop': <{'position': <4>}>, 'org.gnome.Calculator.desktop': <{'position': <5>}>, 'org.gnome.Weather.desktop': <{'position': <6>}>, 'org.gnome.clocks.desktop': <{'position': <7>}>, 'org.gnome.Maps.desktop': <{'position': <8>}>, 'org.gnome.SimpleScan.desktop': <{'position': <9>}>, 'org.gnome.TextEditor.desktop': <{'position': <10>}>, 'org.gnome.Settings.desktop': <{'position': <11>}>, 'org.gnome.Boxes.desktop': <{'position': <12>}>, 'org.gnome.Showtime.desktop': <{'position': <13>}>, 'org.gnome.Snapshot.desktop': <{'position': <14>}>, 'org.gnome.Characters.desktop': <{'position': <15>}>, 'org.gnome.Tour.desktop': <{'position': <16>}>, 'org.gnome.Yelp.desktop': <{'position': <17>}>, 'org.gnome.Software.desktop': <{'position': <18>}>, 'be.alexandervanhee.gradia.desktop': <{'position': <19>}>, 'com.github.jeromerobert.pdfarranger.desktop': <{'position': <20>}>, 'org.onlyoffice.desktopeditors.desktop': <{'position': <21>}>, 'org.gnome.Meld.desktop': <{'position': <22>}>, 'com.mattjakeman.ExtensionManager.desktop': <{'position': <23>}>}, {'org.remmina.Remmina.desktop': <{'position': <0>}>, 'ch.protonmail.protonmail-bridge.desktop': <{'position': <1>}>, 'syncthing-start.desktop': <{'position': <2>}>, 'syncthing-ui.desktop': <{'position': <3>}>, 'emacs.desktop': <{'position': <4>}>, 'emacs-client.desktop': <{'position': <5>}>, 'org.gnome.gitlab.somas.Apostrophe.desktop': <{'position': <6>}>, 'mpv.desktop': <{'position': <7>}>, 'htop.desktop': <{'position': <8>}>, 'com.raspberrypi.rpi-imager.desktop': <{'position': <9>}>}] + [{'System': <{'position': <0>}>, 'Utilities': <{'position': <1>}>, 'org.fedoraproject.MediaWriter.desktop': <{'position': <2>}>, 'org.gnome.Contacts.desktop': <{'position': <3>}>, 'org.gnome.Calendar.desktop': <{'position': <4>}>, 'org.gnome.Calculator.desktop': <{'position': <5>}>, 'org.gnome.Weather.desktop': <{'position': <6>}>, 'org.gnome.clocks.desktop': <{'position': <7>}>, 'org.gnome.Maps.desktop': <{'position': <8>}>, 'org.gnome.SimpleScan.desktop': <{'position': <9>}>, 'org.gnome.TextEditor.desktop': <{'position': <10>}>, 'org.gnome.Settings.desktop': <{'position': <11>}>, 'org.gnome.Boxes.desktop': <{'position': <12>}>, 'org.gnome.Showtime.desktop': <{'position': <13>}>, 'org.gnome.Snapshot.desktop': <{'position': <14>}>, 'org.gnome.Characters.desktop': <{'position': <15>}>, 'org.gnome.Tour.desktop': <{'position': <16>}>, 'org.gnome.Yelp.desktop': <{'position': <17>}>, 'org.gnome.Software.desktop': <{'position': <18>}>, 'be.alexandervanhee.gradia.desktop': <{'position': <19>}>, 'com.github.jeromerobert.pdfarranger.desktop': <{'position': <20>}>, 'org.onlyoffice.desktopeditors.desktop': <{'position': <21>}>, 'org.gnome.Meld.desktop': <{'position': <22>}>, 'com.mattjakeman.ExtensionManager.desktop': <{'position': <23>}>}, {'com.raspberrypi.rpi-imager.desktop': <{'position': <0>}>, 'org.remmina.Remmina.desktop': <{'position': <1>}>, 'com.nextcloud.desktopclient.nextcloud.desktop': <{'position': <2>}>, 'ch.protonmail.protonmail-bridge.desktop': <{'position': <3>}>, 'syncthing-start.desktop': <{'position': <4>}>, 'syncthing-ui.desktop': <{'position': <5>}>, 'emacs.desktop': <{'position': <6>}>, 'emacs-client.desktop': <{'position': <7>}>, 'org.gnome.gitlab.somas.Apostrophe.desktop': <{'position': <8>}>, 'mpv.desktop': <{'position': <9>}>, 'htop.desktop': <{'position': <10>}>, 'ai-media-facefusion.desktop': <{'position': <11>}>, 'ai-media-rvc.desktop': <{'position': <12>}>}] - schema: org.gnome.shell key: disabled-extensions value: >- diff --git a/ansible/roles/desktop_ai_media/defaults/main.yml b/ansible/roles/desktop_ai_media/defaults/main.yml new file mode 100644 index 0000000..d5ec5e8 --- /dev/null +++ b/ansible/roles/desktop_ai_media/defaults/main.yml @@ -0,0 +1,10 @@ +--- +desktop_ai_media_enabled: false +desktop_ai_media_root: "{{ user_home }}/.local/share/ai-media" +desktop_ai_media_build_root: "{{ user_home }}/.local/share/ai-media-build" +desktop_ai_media_debian_snapshot: "20261013T000000Z" +desktop_ai_media_base_image: >- + docker.io/library/python@sha256:34386ef0cb081344d7ec1c103ba398e6e9f64e9ab3a1509accc92a4e24a07258 +desktop_ai_media_facefusion_revision: 72470819a0373be3388b3929c8f8f311f418fc3c +desktop_ai_media_rvc_revision: 81eed5e8f68b6bed1789f682fe78cdd324495afc +desktop_ai_media_apps: [facefusion, rvc] diff --git a/ansible/roles/desktop_ai_media/files/check_storage.py b/ansible/roles/desktop_ai_media/files/check_storage.py new file mode 100644 index 0000000..62fb635 --- /dev/null +++ b/ansible/roles/desktop_ai_media/files/check_storage.py @@ -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") diff --git a/ansible/roles/desktop_ai_media/files/prepare.py b/ansible/roles/desktop_ai_media/files/prepare.py new file mode 100644 index 0000000..1bb5f7e --- /dev/null +++ b/ansible/roles/desktop_ai_media/files/prepare.py @@ -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") diff --git a/ansible/roles/desktop_ai_media/files/requirements-facefusion.lock b/ansible/roles/desktop_ai_media/files/requirements-facefusion.lock new file mode 100644 index 0000000..1585f9b --- /dev/null +++ b/ansible/roles/desktop_ai_media/files/requirements-facefusion.lock @@ -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 diff --git a/ansible/roles/desktop_ai_media/files/requirements-rvc.lock b/ansible/roles/desktop_ai_media/files/requirements-rvc.lock new file mode 100644 index 0000000..2c713d7 --- /dev/null +++ b/ansible/roles/desktop_ai_media/files/requirements-rvc.lock @@ -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 diff --git a/ansible/roles/desktop_ai_media/files/session.py b/ansible/roles/desktop_ai_media/files/session.py new file mode 100644 index 0000000..7083130 --- /dev/null +++ b/ansible/roles/desktop_ai_media/files/session.py @@ -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) diff --git a/ansible/roles/desktop_ai_media/files/verify.py b/ansible/roles/desktop_ai_media/files/verify.py new file mode 100644 index 0000000..a3ab39a --- /dev/null +++ b/ansible/roles/desktop_ai_media/files/verify.py @@ -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") diff --git a/ansible/roles/desktop_ai_media/tasks/main.yml b/ansible/roles/desktop_ai_media/tasks/main.yml new file mode 100644 index 0000000..34c0883 --- /dev/null +++ b/ansible/roles/desktop_ai_media/tasks/main.yml @@ -0,0 +1,217 @@ +--- +- name: Configure isolated desktop media tools as the desktop user + become: false + block: + - name: Load pinned public model manifest + ansible.builtin.include_vars: models.yml + + - name: Identify unprivileged desktop user + ansible.builtin.command: + argv: [id, -un] + register: desktop_ai_media_user + changed_when: false + check_mode: false + + - name: Verify local Fedora desktop scope + ansible.builtin.assert: + that: + - "'platform_fedora' in group_names" + - "'desktop_gnome' in group_names" + - ansible_connection == 'local' + - desktop_ai_media_user.stdout == username + - ansible_facts.architecture == 'x86_64' + - desktop_ai_media_root.startswith(user_home + '/') + - desktop_ai_media_root != user_home + - desktop_ai_media_build_root != desktop_ai_media_root + - desktop_ai_media_facefusion_revision is match('^[0-9a-f]{40}$') + - desktop_ai_media_rvc_revision is match('^[0-9a-f]{40}$') + - "'@sha256:' in desktop_ai_media_base_image" + - desktop_ai_media_debian_snapshot is match('^[0-9]{8}T[0-9]{6}Z$') + - desktop_ai_media_public_models | length > 0 + - >- + desktop_ai_media_apps | difference( + desktop_ai_media_public_models | map(attribute='app') | list) | length == 0 + + - name: Verify existing rootless Podman runtime + ansible.builtin.command: + argv: [podman, --remote=false, info, --format, "{{ '{{.Host.Security.Rootless}}' }}"] + register: desktop_ai_media_podman + changed_when: false + check_mode: false + + - name: Require rootless containers + ansible.builtin.assert: + that: desktop_ai_media_podman.stdout == 'true' + + - name: Reject remote or synchronized media storage before provisioning + ansible.builtin.command: + argv: [python3, "-", "{{ desktop_ai_media_root }}"] + stdin: "{{ lookup('ansible.builtin.file', role_path + '/files/check_storage.py') }}" + changed_when: false + check_mode: false + + - name: Create private application and media directories + ansible.builtin.file: + path: "{{ item }}" + state: directory + mode: "0700" + loop: + - "{{ desktop_ai_media_root }}" + - "{{ desktop_ai_media_root }}/input" + - "{{ desktop_ai_media_root }}/input/voice" + - "{{ desktop_ai_media_root }}/output" + - "{{ desktop_ai_media_root }}/models" + - "{{ desktop_ai_media_root }}/models/weights" + - "{{ desktop_ai_media_root }}/models/indices" + - "{{ desktop_ai_media_root }}/state" + - "{{ desktop_ai_media_root }}/state/facefusion" + - "{{ desktop_ai_media_root }}/state/rvc" + - "{{ desktop_ai_media_build_root }}" + + - name: Ensure user launcher directories exist without changing existing permissions + ansible.builtin.file: + path: "{{ item }}" + state: directory + loop: + - "{{ user_home }}/.local/bin" + - "{{ user_home }}/.local/share/applications" + + - name: Install runtime and model preparation code into the data-free build context + ansible.builtin.copy: + src: "{{ item }}" + dest: "{{ desktop_ai_media_build_root }}/{{ item }}" + mode: "0644" + loop: [session.py, prepare.py, verify.py, check_storage.py] + register: desktop_ai_media_support + + - name: Create public model cache directories + ansible.builtin.file: + path: "{{ desktop_ai_media_build_root }}/models/{{ item.app }}/{{ item.path | dirname }}" + state: directory + mode: "0700" + loop: "{{ desktop_ai_media_public_models }}" + loop_control: + label: "{{ item.app }}/{{ item.path }}" + + - name: Cache public models using pinned SHA256 checksums without personal data + ansible.builtin.get_url: + url: "{{ item.url }}" + dest: "{{ desktop_ai_media_build_root }}/models/{{ item.app }}/{{ item.path }}" + checksum: "sha256:{{ item.sha256 }}" + mode: "0644" + timeout: 60 + use_netrc: false + use_proxy: false + loop: "{{ desktop_ai_media_public_models }}" + loop_control: + label: "{{ item.app }}/{{ item.path }}" + register: desktop_ai_media_model_cache + + - name: Install complete Python dependency locks + ansible.builtin.copy: + src: "requirements-{{ item }}.lock" + dest: "{{ desktop_ai_media_build_root }}/requirements-{{ item }}.lock" + mode: "0644" + loop: "{{ desktop_ai_media_apps }}" + register: desktop_ai_media_locks + + - name: Restrict the build context to code and checksum-pinned public models + ansible.builtin.template: + src: containerignore.j2 + dest: "{{ desktop_ai_media_build_root }}/.containerignore" + mode: "0644" + register: desktop_ai_media_ignore + + - name: Render separate pinned application builds + ansible.builtin.template: + src: Containerfile.j2 + dest: "{{ desktop_ai_media_build_root }}/Containerfile.{{ item }}" + mode: "0644" + loop: "{{ desktop_ai_media_apps }}" + register: desktop_ai_media_containerfiles + + - name: Fingerprint the complete application build specification + ansible.builtin.set_fact: + desktop_ai_media_build_keys: >- + {{ desktop_ai_media_build_keys | default({}) | combine({ + item: ( + lookup('ansible.builtin.template', role_path + '/templates/Containerfile.j2') + + lookup('ansible.builtin.file', role_path + '/files/prepare.py') + + lookup('ansible.builtin.file', role_path + '/files/session.py') + + lookup('ansible.builtin.file', role_path + '/files/verify.py') + + lookup('ansible.builtin.file', role_path + '/files/requirements-' + item + '.lock') + + lookup('ansible.builtin.file', role_path + '/templates/containerignore.j2') + ) | hash('sha256') + }) }} + loop: "{{ desktop_ai_media_apps }}" + + - name: Inspect installed media images + ansible.builtin.command: + argv: [podman, --remote=false, image, exists, "localhost/ai-media-{{ item }}:managed"] + loop: "{{ desktop_ai_media_apps }}" + register: desktop_ai_media_images + failed_when: desktop_ai_media_images.rc not in [0, 1] + changed_when: false + check_mode: false + + - name: Inspect committed image build fingerprints + ansible.builtin.command: + argv: + - podman + - --remote=false + - image + - inspect + - --format + - "{{ '{{ index .Labels \"io.fscotto.ai-media.build-key\" }}' }}" + - "localhost/ai-media-{{ item.item }}:managed" + loop: "{{ desktop_ai_media_images.results }}" + loop_control: + label: "{{ item.item }}" + when: item.rc == 0 + register: desktop_ai_media_image_keys + changed_when: false + check_mode: false + + - name: Build media images without mounting personal data + ansible.builtin.command: + argv: + - podman + - --remote=false + - build + - --http-proxy=false + - --pull=missing + - --label + - "io.fscotto.ai-media.build-key={{ desktop_ai_media_build_keys[item.item] }}" + - --tag + - "localhost/ai-media-{{ item.item }}:managed" + - --file + - "{{ desktop_ai_media_build_root }}/Containerfile.{{ item.item }}" + - "{{ desktop_ai_media_build_root }}" + loop: "{{ desktop_ai_media_images.results }}" + loop_control: + label: "{{ item.item }}" + when: >- + item.rc != 0 or + desktop_ai_media_image_keys.results[desktop_ai_media_apps.index(item.item)].stdout | default('') != + desktop_ai_media_build_keys[item.item] + changed_when: true + timeout: 3600 + + - name: Install offline launcher + ansible.builtin.template: + src: ai-media.j2 + dest: "{{ user_home }}/.local/bin/ai-media" + mode: "0755" + + - name: Install manual offline desktop entries + ansible.builtin.template: + src: application.desktop.j2 + dest: "{{ user_home }}/.local/share/applications/ai-media-{{ item }}.desktop" + mode: "0644" + loop: "{{ desktop_ai_media_apps }}" + + - name: Verify offline networking and application readiness without personal files + ansible.builtin.command: + argv: ["{{ user_home }}/.local/bin/ai-media", verify] + changed_when: false + when: not ansible_check_mode diff --git a/ansible/roles/desktop_ai_media/templates/Containerfile.j2 b/ansible/roles/desktop_ai_media/templates/Containerfile.j2 new file mode 100644 index 0000000..3a15ed5 --- /dev/null +++ b/ansible/roles/desktop_ai_media/templates/Containerfile.j2 @@ -0,0 +1,40 @@ +FROM {{ desktop_ai_media_base_image }} +LABEL io.fscotto.ai-media.models="{{ desktop_ai_media_public_models | selectattr('app', 'equalto', item) | list | to_json | hash('sha256') }}" +ENV DEBIAN_FRONTEND=noninteractive PIP_DISABLE_PIP_VERSION_CHECK=1 +RUN sed -i \ + -e 's|http://deb.debian.org/debian$|https://snapshot.debian.org/archive/debian/{{ desktop_ai_media_debian_snapshot }}/|' \ + -e 's|http://deb.debian.org/debian-security$|https://snapshot.debian.org/archive/debian-security/{{ desktop_ai_media_debian_snapshot }}/|' \ + /etc/apt/sources.list.d/debian.sources \ + && apt-get -o Acquire::Check-Valid-Until=false update \ + && apt-get install -y --no-install-recommends \ + ca-certificates curl git ffmpeg firefox-esr fonts-dejavu-core libgl1 libglib2.0-0 libportaudio2 \ + && rm -rf /var/lib/apt/lists/* +COPY requirements-{{ item }}.lock /opt/requirements.lock +WORKDIR /opt/app +{% if item == 'facefusion' %} +RUN git init . && git remote add origin https://github.com/facefusion/facefusion.git \ + && git fetch --depth 1 origin {{ desktop_ai_media_facefusion_revision }} \ + && git checkout --detach FETCH_HEAD && rm -rf .git \ + && pip install --no-cache-dir -r /opt/requirements.lock +{% else %} +RUN git init . && git remote add origin https://github.com/RVC-Project/Retrieval-based-Voice-Conversion-WebUI.git \ + && git fetch --depth 1 origin {{ desktop_ai_media_rvc_revision }} \ + && git checkout --detach FETCH_HEAD && rm -rf .git \ + && pip install --no-cache-dir -r /opt/requirements.lock +{% endif %} +{% for model in desktop_ai_media_public_models if model.app == item %} +COPY models/{{ model.app }}/{{ model.path }} /opt/app/{{ model.path }} +{% endfor %} +COPY prepare.py /opt/ +RUN python /opt/prepare.py {{ item }} \ + && pip freeze --all > /opt/python-requirements.lock \ + && test -s /opt/model-checksums.sha256 +COPY session.py verify.py /opt/ +RUN mkdir -p /work/input /work/output /work/state /work/models /home/media +ENV GRADIO_ANALYTICS_ENABLED=False HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \ + HF_HUB_DISABLE_TELEMETRY=1 DO_NOT_TRACK=1 HOME=/home/media \ + XDG_RUNTIME_DIR=/run/media MOZ_ENABLE_WAYLAND=1 GTK_USE_PORTAL=0 \ + LIBGL_ALWAYS_SOFTWARE=1 GRADIO_SERVER_NAME=127.0.0.1 GRADIO_SERVER_PORT=7860 \ + PYTHONPATH=/opt/app PYTHONSAFEPATH=1 PYTHONDONTWRITEBYTECODE=1 NUMBA_CACHE_DIR=/tmp/numba MPLCONFIGDIR=/tmp/matplotlib \ + GRADIO_TEMP_DIR=/tmp/gradio APP={{ item }} +ENTRYPOINT ["python", "/opt/session.py"] diff --git a/ansible/roles/desktop_ai_media/templates/ai-media.j2 b/ansible/roles/desktop_ai_media/templates/ai-media.j2 new file mode 100644 index 0000000..f7f03b3 --- /dev/null +++ b/ansible/roles/desktop_ai_media/templates/ai-media.j2 @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +set -euo pipefail +root={{ desktop_ai_media_root | quote }} +app="${1:-}" +case "$app" in + facefusion|rvc) shift ;; + ffmpeg) app=facefusion; shift; set -- ffmpeg "$@" ;; + verify) + for tool in facefusion rvc; do + podman --remote=false run --rm --pull=never --network=none --read-only \ + --cap-drop=ALL --cap-add=SYS_CHROOT \ + --security-opt=no-new-privileges --userns=keep-id --http-proxy=false \ + --tmpfs "/tmp:rw,nosuid,nodev,size=4g,mode=1777" \ + --tmpfs "/home/media:rw,nosuid,nodev,size=128m,mode=1777" \ + --tmpfs "/work/state:rw,nosuid,nodev,size=128m,mode=1777" \ + --tmpfs "/work/models:rw,nosuid,nodev,size=128m,mode=1777" \ + "localhost/ai-media-$tool:managed" verify + done + exit 0 ;; + *) echo "Usage: ai-media {facefusion|rvc|ffmpeg|verify} [cli ...]" >&2; exit 2 ;; +esac +# 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 + [[ -d "$path" && "$(realpath -- "$path")" == "$path" ]] || { + echo "Unsafe or missing media directory: $path" >&2; exit 1; + } +done +python3 {{ (desktop_ai_media_build_root + "/check_storage.py") | quote }} "$root" +# Run interactive sessions under the user manager, not the launching terminal. +# No autostart or automatic restart: recovering a training run remains explicit. +if [[ "$app" == rvc || "$app" == facefusion ]] && [[ $# -eq 0 ]]; then + : "${XDG_RUNTIME_DIR:?Run this launcher from the GNOME Wayland session}" + : "${WAYLAND_DISPLAY:?A Wayland session is required}" + [[ "$WAYLAND_DISPLAY" != */* && -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]] || exit 1 + active=$(podman --remote=false ps --filter "ancestor=localhost/ai-media-$app:managed" --format '{{ '{{.ID}}' }}') + if [[ -n "$active" ]]; then + echo "$app is already running; leave its training session open." >&2 + exit 1 + fi + exec systemd-run --user --collect --unit="ai-media-$app" \ + --property=Type=exec --property=Restart=no --property=Delegate=yes \ + --setenv="XDG_RUNTIME_DIR=$XDG_RUNTIME_DIR" --setenv="WAYLAND_DISPLAY=$WAYLAND_DISPLAY" \ + -- /usr/bin/bash "$(realpath -- "$0")" "$app" --foreground +fi +if [[ "${1:-}" == --foreground ]]; then + shift +fi +args=( + run --rm --pull=never --network=none --read-only --userns=keep-id --http-proxy=false + --cap-drop=ALL --security-opt=no-new-privileges + --tmpfs "/tmp:rw,nosuid,nodev,size=8g,mode=1777" + --tmpfs "/home/media:rw,nosuid,nodev,size=128m,mode=1777" + --shm-size=512m + --volume "$root/input:/work/input:ro,Z" + --volume "$root/output:/work/output:rw,Z" + --volume "$root/models:/work/models:ro,Z" + --volume "$root/state/$app:/work/state:rw,Z" +) +if [[ "${1:-}" != cli && "${1:-}" != ffmpeg ]]; then + : "${XDG_RUNTIME_DIR:?Run this launcher from the GNOME Wayland session}" + : "${WAYLAND_DISPLAY:?A Wayland session is required}" + [[ "$WAYLAND_DISPLAY" != */* && -S "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY" ]] || exit 1 + # Share only the display socket, never the runtime directory, D-Bus, home + # directory or host browser. Do not relabel the compositor's socket. + args+=( + --cap-add=SYS_CHROOT + --security-opt label=disable + --tmpfs "/run/media:rw,nosuid,nodev,size=1m,mode=1777" + --volume "$XDG_RUNTIME_DIR/$WAYLAND_DISPLAY:/run/media/wayland-0:ro" + --env WAYLAND_DISPLAY=wayland-0 + ) + if [[ -S "$XDG_RUNTIME_DIR/pulse/native" ]]; then + args+=( + --volume "$XDG_RUNTIME_DIR/pulse/native:/run/media/pulse-native:ro" + --env PULSE_SERVER=unix:/run/media/pulse-native + ) + fi +fi +exec podman --remote=false "${args[@]}" "localhost/ai-media-$app:managed" "$@" diff --git a/ansible/roles/desktop_ai_media/templates/application.desktop.j2 b/ansible/roles/desktop_ai_media/templates/application.desktop.j2 new file mode 100644 index 0000000..d77926a --- /dev/null +++ b/ansible/roles/desktop_ai_media/templates/application.desktop.j2 @@ -0,0 +1,7 @@ +[Desktop Entry] +Type=Application +Name={{ 'FaceFusion' if item == 'facefusion' else 'RVC Voice Conversion' }} (offline) +Exec={{ user_home }}/.local/bin/ai-media {{ item }} +Terminal=false +Categories=AudioVideo; +StartupNotify=false diff --git a/ansible/roles/desktop_ai_media/templates/containerignore.j2 b/ansible/roles/desktop_ai_media/templates/containerignore.j2 new file mode 100644 index 0000000..6445818 --- /dev/null +++ b/ansible/roles/desktop_ai_media/templates/containerignore.j2 @@ -0,0 +1,15 @@ +* +!Containerfile.* +!prepare.py +!session.py +!verify.py +!requirements-facefusion.lock +!requirements-rvc.lock +!models/ +{% for model in desktop_ai_media_public_models %} +!models/{{ model.app }}/ +{% for depth in range(1, model.path.split('/') | length) %} +!models/{{ model.app }}/{{ model.path.split('/')[:depth] | join('/') }}/ +{% endfor %} +!models/{{ model.app }}/{{ model.path }} +{% endfor %} diff --git a/ansible/roles/desktop_ai_media/tests/test_launcher.py b/ansible/roles/desktop_ai_media/tests/test_launcher.py new file mode 100644 index 0000000..04eb3ac --- /dev/null +++ b/ansible/roles/desktop_ai_media/tests/test_launcher.py @@ -0,0 +1,108 @@ +import json +import os +from pathlib import Path +import socket +import subprocess +import tempfile +import unittest + +from jinja2 import Environment +import shlex + +ROLE = Path(__file__).resolve().parents[1] + + +class LauncherTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.media = self.root / '.local/share/ai-media' + for directory in ('input', 'output', 'models', 'state/facefusion', 'state/rvc'): + (self.media / directory).mkdir(parents=True) + environment = Environment() + environment.filters['quote'] = shlex.quote + self.launcher = self.root / 'ai-media' + self.launcher.write_text(environment.from_string( + (ROLE / 'templates/ai-media.j2').read_text() + ).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.log = self.root / 'podman.json' + podman = self.root / 'podman' + podman.write_text('#!/usr/bin/python3\nimport json,os,sys\n' + 'open(os.environ["TEST_LOG"], "w").write(json.dumps(sys.argv[1:]))\n') + podman.chmod(0o755) + self.env = dict(os.environ, PATH=str(self.root) + ':' + os.environ['PATH'], + TEST_LOG=str(self.log), HOME=str(self.root)) + + def launch(self, *args): + return subprocess.run(['bash', str(self.launcher), *args], env=self.env, + capture_output=True, text=True) + + def test_cli_has_no_network_or_host_home(self): + result = self.launch('facefusion', 'cli', '--help') + self.assertEqual(result.returncode, 0, result.stderr) + args = json.loads(self.log.read_text()) + for flag in ('--network=none', '--pull=never', '--read-only', + '--security-opt=no-new-privileges', '--cap-drop=ALL'): + self.assertIn(flag, args) + self.assertIn(str(self.media / 'input') + ':/work/input:ro,Z', args) + self.assertNotIn('--privileged', args) + self.assertNotIn('--security-opt', args) + self.assertNotIn('label=disable', args) + + def test_gui_exposes_only_wayland_socket(self): + self.env.update(XDG_RUNTIME_DIR=str(self.root), WAYLAND_DISPLAY='wayland-0') + with socket.socket(socket.AF_UNIX) as sock: + sock.bind(str(self.root / 'wayland-0')) + result = self.launch('rvc', '--foreground') + self.assertEqual(result.returncode, 0, result.stderr) + args = json.loads(self.log.read_text()) + self.assertIn('--network=none', args) + self.assertIn(str(self.root / 'wayland-0') + ':/run/media/wayland-0:ro', args) + self.assertIn('/run/media:rw,nosuid,nodev,size=1m,mode=1777', args) + self.assertFalse(any('uid=' in arg or 'gid=' in arg for arg in args)) + self.assertNotIn('--publish', args) + self.assertFalse(any('dbus' in arg for arg in args)) + + def test_default_gui_uses_independent_user_service(self): + self.env.update(XDG_RUNTIME_DIR=str(self.root), WAYLAND_DISPLAY='wayland-0') + 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) + with socket.socket(socket.AF_UNIX) as sock: + sock.bind(str(self.root / 'wayland-0')) + result = self.launch('rvc') + self.assertEqual(result.returncode, 0, result.stderr) + args = json.loads(self.log.read_text()) + self.assertIn('--user', args) + self.assertIn('--unit=ai-media-rvc', args) + self.assertIn('--property=Restart=no', args) + self.assertIn('--foreground', args) + self.assertNotIn('--scope', args) + self.assertNotIn('--pty', args) + self.assertNotIn('--wait', args) + + def test_symlinked_input_is_rejected(self): + (self.media / 'input').rmdir() + (self.media / 'input').symlink_to(self.root) + self.assertNotEqual(self.launch('facefusion', 'cli', '--help').returncode, 0) + self.assertFalse(self.log.exists()) + + def test_synced_storage_is_rejected(self): + directory = self.root / '.config/Nextcloud' + directory.mkdir(parents=True) + (directory / 'nextcloud.cfg').write_text( + '[Accounts]\n0\\Folders\\1\\localPath=' + str(self.media) + '\n' + ) + self.assertNotEqual(self.launch('facefusion', 'cli', '--help').returncode, 0) + self.assertFalse(self.log.exists()) + + def test_invalid_tool_is_rejected(self): + self.assertEqual(self.launch('--network=host').returncode, 2) + self.assertFalse(self.log.exists()) + + +if __name__ == '__main__': + unittest.main() diff --git a/ansible/roles/desktop_ai_media/vars/models.yml b/ansible/roles/desktop_ai_media/vars/models.yml new file mode 100644 index 0000000..746ed4a --- /dev/null +++ b/ansible/roles/desktop_ai_media/vars/models.yml @@ -0,0 +1,134 @@ +--- +desktop_ai_media_public_models: + - app: facefusion + path: .assets/models/2dfan4.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/2dfan4.hash + sha256: e6a6ef99b10b9fdb790c790879ca201f7afbe52560e4379248922324a9d503e8 + - app: facefusion + path: .assets/models/2dfan4.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/2dfan4.onnx + sha256: 678c6fa539d52335a31c980feefdf4a6e02d781d83dce00af8a894f114557285 + - app: facefusion + path: .assets/models/arcface_w600k_r50.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/arcface_w600k_r50.hash + sha256: e3a6d709939a81fe09e71c7d36f96d54a0deede904e31a38c191a1904e808371 + - app: facefusion + path: .assets/models/arcface_w600k_r50.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/arcface_w600k_r50.onnx + sha256: f1f79dc3b0b79a69f94799af1fffebff09fbd78fd96a275fd8f0cbbea23270d1 + - app: facefusion + path: .assets/models/bisenet_resnet_34.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/bisenet_resnet_34.hash + sha256: bfca5e43ca55110701ab691d864cacfddccad324dc42043aea8c001a949ce1f8 + - app: facefusion + path: .assets/models/bisenet_resnet_34.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/bisenet_resnet_34.onnx + sha256: 4a0b8c958a3c938913bd06a8365dbb3c8761afba6ecbf0d14b3b1f77eb230c96 + - app: facefusion + path: .assets/models/fairface.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fairface.hash + sha256: e232c933114a6c9ce446195e4a96bf1c3327dd31c13165849cd00f9f19a2ea62 + - app: facefusion + path: .assets/models/fairface.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fairface.onnx + sha256: b176b1e4b0739496e7943af7ba4ff306271fecf837bca5ec5d9a48201959db37 + - app: facefusion + path: .assets/models/fan_68_5.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fan_68_5.hash + sha256: 092d902410959b3ce01294d7c1ad157f1c602e3918238117e7ef87157be9534e + - app: facefusion + path: .assets/models/fan_68_5.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/fan_68_5.onnx + sha256: ea05f7d9d014ae1d9cdc6e9c72643d8f00d198b5db3fdd384148ddff499a613e + - app: facefusion + path: .assets/models/hyperswap_1a_256.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/hyperswap_1a_256.hash + sha256: 70b33d0a9d6044847d9b29f9d08ce7afc140a2cada5b4b5f532bbd6440ba48c1 + - app: facefusion + path: .assets/models/hyperswap_1a_256.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/hyperswap_1a_256.onnx + sha256: c0e98a8a03a238f461ed3d2570e426b49f46745ee400854a60dceeb70c246add + - app: facefusion + path: .assets/models/kim_vocal_2.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/kim_vocal_2.hash + sha256: fcd81ca30adf430b697fe58d60183031173c8ab0ca82efef308d652b1afb4197 + - app: facefusion + path: .assets/models/kim_vocal_2.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/kim_vocal_2.onnx + sha256: fbde1fd7d35a6b1785add2225ce03255a01ccef6c8a5fb7b2ccd4e0c1e9097f7 + - app: facefusion + path: .assets/models/nsfw_1.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_1.hash + sha256: 48c61a15ffcda1ae9e6d4c790224072c8e5648d4ba2f767cf4cfe0be7e282853 + - app: facefusion + path: .assets/models/nsfw_1.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_1.onnx + sha256: 3debfd72763bc931dd308f57d1e9299ae13bb309d14ddbdc17ce8f1fd42f96af + - app: facefusion + path: .assets/models/nsfw_2.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_2.hash + sha256: 64cbc0c1a4d72e181fae364281b6d2130be3b87d5784909c5a29adf436f09a01 + - app: facefusion + path: .assets/models/nsfw_2.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_2.onnx + sha256: 5aae1806ce44e3c27fab0a7d44eed581dd25ca71a4387ff809a191c98239c1be + - app: facefusion + path: .assets/models/nsfw_3.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_3.hash + sha256: b15c591d8177511959174a0c6761827e3bf9c0aa1d63aaa79645d9fc9a4e774b + - app: facefusion + path: .assets/models/nsfw_3.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.3.0/nsfw_3.onnx + sha256: 778139fb930240ac39812a1480295bfc5dc2cec8a8e46ee6b453481d600c0fa2 + - app: facefusion + path: .assets/models/xseg_1.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.1.0/xseg_1.hash + sha256: da3648ccecaa79f3be5ca0e1c3713f775504dd5c5dff716c095925132c02b08e + - app: facefusion + path: .assets/models/xseg_1.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.1.0/xseg_1.onnx + sha256: c4d1498b8a03b5fe2a3a5d2ef2a0402ab03bd51edaf5b2d8d5fb764702a97dd3 + - app: facefusion + path: .assets/models/yoloface_8n.hash + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/yoloface_8n.hash + sha256: 7a4bd7e1a8cd938db2234dba41d4a8b7719bedbf7496d35510927cbd4b71683f + - app: facefusion + path: .assets/models/yoloface_8n.onnx + url: https://github.com/facefusion/facefusion-assets/releases/download/models-3.0.0/yoloface_8n.onnx + sha256: 821cdbb1e65fbbabdde7dd0933f754797a343e56fd962729c61ffcefcd135929 + - app: rvc + path: assets/hubert_base/config.json + url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/hubert_base/config.json + sha256: 0346950779dfb7f9316fa74ed846e2b8a22a08eedfdc5387b73f327cb1a4a7cf + - app: rvc + path: assets/hubert_base/preprocessor_config.json + url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/hubert_base/preprocessor_config.json + sha256: 7c1976a680fb7acc757cd36fb08eef878fa36c70b4c9d2d595df9c608bbbbf0e + - app: rvc + path: assets/hubert_base/pytorch_model.bin + url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/hubert_base/pytorch_model.bin + sha256: cc8c20f4b90a520757260197a3ff2505705a7adbd20ad9eeaa4e1a9b38442ef5 + - app: rvc + path: assets/rmvpe/rmvpe.pt + url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/rmvpe.pt + sha256: 6d62215f4306e3ca278246188607209f09af3dc77ed4232efdd069798c4ec193 + - app: rvc + path: assets/mute.zip + url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/mute.zip + sha256: ee948e85213e4ed2f2ba2f8dfcee810bfd0b63131d91450e920bbe1cbd0321d0 + - app: rvc + path: assets/pretrained_v2/f0D40k.pth + url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pretrained_v2/f0D40k.pth + sha256: 6b6ab091e70801b28e3f41f335f2fc5f3f35c75b39ae2628d419644ec2b0fa09 + - app: rvc + path: assets/pretrained_v2/f0G40k.pth + url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pretrained_v2/f0G40k.pth + sha256: 3b2c44035e782c4b14ddc0bede9e2f4a724d025cd073f736d4f43708453adfcb + - app: rvc + path: assets/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.ckpt + url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.ckpt + sha256: 97c9e1011924ff647d147b474638c161b80586fd5b9e83fab59cbbb70014bf62 + - app: rvc + path: assets/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.yaml + url: https://huggingface.co/lj1995/VoiceConversionWebUI/resolve/e6d0c1a17da07c33557852f9dfa2bd44cc75737d/pymss_weights/model_bs_roformer_ep_368_sdr_12.9628.yaml + sha256: 105fd8e6a1ef1b038db2aa657a9f9696283d506dbc815bd7134a57aa80ec9f10 diff --git a/ansible/site.yml b/ansible/site.yml index 653484b..89da00c 100644 --- a/ansible/site.yml +++ b/ansible/site.yml @@ -122,6 +122,9 @@ roles: - profile_desktop_gnome + - role: desktop_ai_media + when: desktop_ai_media_enabled | default(false) | bool + tags: [ai_media] - name: Configure Fedora workstation development layer hosts: workstation_dev_fedora