Files
Athena-Deck/deploy/applio-web/backend/app/adapters/real_runner.py
T
Mikei386 06cacafbad Add native Applio RVC and preserve the custom studio UI
Pin Applio 3.6.5 and verified basis assets, migrate private voice provenance, and coordinate conversion/live/training with Deck GPU leases. Prepare an inactive voice profile and a restricted studio container. Move CUDA and Torch caches out of the small temporary filesystem to prevent OmniVoice reference failures. Package app updates from the explicit allowlist in one Docker layer.
2026-10-05 10:02:07 +02:00

590 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Real Applio runner – executes actual Applio CLI commands via docker exec."""
from __future__ import annotations
import logging
import re
import subprocess
import threading
import time
from pathlib import Path
from ..config import get_settings
from ..jobs.enums import JobPhase, JobType
from ..jobs.models import Job
from .base import Runner
logger = logging.getLogger(__name__)
class RealApplioRunner(Runner):
"""Executes real Applio CLI commands inside the Docker container."""
def __init__(self) -> None:
self._settings = get_settings()
def name(self) -> str:
return "Applio-Runner (echt)"
def is_available(self) -> bool:
"""Check whether the container and required Applio executables are usable."""
try:
result = subprocess.run(
["docker", "inspect", "-f", "{{.State.Running}}", self._settings.applio_container],
capture_output=True,
text=True,
timeout=10,
check=False,
)
if result.returncode != 0 or result.stdout.strip() != "true":
return False
core_path = str(Path(self._settings.applio_workdir) / self._settings.applio_core_py)
probe = subprocess.run(
[
"docker", "exec", self._settings.applio_container, "sh", "-c",
'test -x "$1" && test -f "$2"', "mikes-applio-probe",
str(self._settings.applio_python), core_path,
],
capture_output=True,
text=True,
timeout=10,
check=False,
)
return probe.returncode == 0
except (subprocess.TimeoutExpired, FileNotFoundError):
return False
def execute(self, job: Job, cancel_event: threading.Event) -> None:
if not self.is_available():
job.mark_failed(
"Applio-Container ist nicht erreichbar. "
"Der Container muss laufen, bevor echte Aufträge ausgeführt werden können."
)
return
job.add_log(f"Applio-Runner gestartet (Job-Typ: {job.type.value})")
try:
if job.type == JobType.CONVERT:
self._run_convert(job, cancel_event)
elif job.type == JobType.TTS_CONVERT:
self._run_tts_convert(job, cancel_event)
elif job.type == JobType.PREPROCESS:
self._run_preprocess(job, cancel_event)
elif job.type == JobType.EXTRACT:
self._run_extract(job, cancel_event)
elif job.type == JobType.TRAIN:
self._run_train(job, cancel_event)
elif job.type == JobType.INDEX:
self._run_index(job, cancel_event)
else:
job.mark_failed(f"Unbekannter Job-Typ: {job.type.value}")
except _CancelledError:
job.mark_cancelled()
except _ApplioError as e:
job.mark_failed(str(e))
except Exception as e:
logger.exception("Real runner crashed")
job.mark_failed(f"Unerwarteter Fehler: {e}")
def _build_cmd(self, subcommand: str, args: list[str]) -> list[str]:
"""Build a safe docker exec command with argument list (no shell)."""
return [
"docker",
"exec",
"-w",
self._settings.applio_workdir,
self._settings.applio_container,
str(self._settings.applio_python),
self._settings.applio_core_py,
subcommand,
*args,
]
def _run_cmd(
self,
cmd: list[str],
job: Job,
cancel_event: threading.Event,
timeout: int = 3600,
) -> subprocess.CompletedProcess:
"""Run a command, streaming output to job log, checking for cancellation."""
job.add_log(f"Ausführe: {' '.join(cmd[:6])} ...")
pid_file = f"/tmp/mikes_applio_{job.id}.pid"
wrapped_cmd = [
*cmd[:5],
"sh", "-c", 'printf "%s" "$$" > "$1"; shift; exec "$@"',
"mikes-applio-runner", pid_file, *cmd[5:],
]
proc = subprocess.Popen(
wrapped_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
# Read output in a thread to avoid blocking
output_lines: list[str] = []
error_lines: list[str] = []
def read_stream(stream, lines: list[str]):
for line in stream:
clean_line = line.rstrip()
lines.append(clean_line)
job.add_log(clean_line)
if job.type == JobType.TRAIN:
match = re.search(r"(?:epoch|Epoch)[^0-9]*(\d+)", clean_line)
if match:
current = int(match.group(1))
total = max(1, int(job.parameters.get("total_epoch", 1)))
if 0 < current <= total:
job.progress = min(99.0, current / total * 100.0)
job.progress_message = f"Training: Epoche {current} von {total}"
import concurrent.futures
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
f_out = executor.submit(read_stream, proc.stdout, output_lines)
f_err = executor.submit(read_stream, proc.stderr, error_lines)
# Wait for process or cancellation
start = time.time()
while proc.poll() is None:
if cancel_event.is_set():
self._stop_container_process(pid_file)
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
raise _CancelledError()
if time.time() - start > timeout:
self._stop_container_process(pid_file)
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
raise _ApplioError(f"Zeitüberschreitung nach {timeout}s")
time.sleep(0.5)
f_out.result()
f_err.result()
subprocess.run(
["docker", "exec", self._settings.applio_container, "rm", "-f", pid_file],
capture_output=True,
timeout=10,
check=False,
)
result = subprocess.CompletedProcess(
cmd, proc.returncode, stdout="".join(output_lines), stderr="".join(error_lines)
)
if result.returncode != 0:
stderr_tail = "\n".join(error_lines[-20:])
raise _ApplioError(
f"Applio-Command fehlgeschlagen (Exit-Code {result.returncode}):\n{stderr_tail}"
)
return result
def _stop_container_process(self, pid_file: str) -> None:
"""Terminate the actual process inside Applio, not only the docker CLI client."""
subprocess.run(
[
"docker", "exec", self._settings.applio_container,
"sh", "-c", 'test ! -f "$1" || kill -TERM "$(cat "$1")"',
"mikes-applio-stop", pid_file,
],
capture_output=True,
timeout=15,
check=False,
)
subprocess.run(
["docker", "exec", self._settings.applio_container, "rm", "-f", pid_file],
capture_output=True,
timeout=10,
check=False,
)
def _map_host_to_container(self, host_path: str) -> str:
"""Map a path visible to this UI container into the Applio container."""
if not host_path:
return ""
source = Path(host_path).resolve()
mappings = (
(self._settings.uploads_dir.resolve(), self._settings.applio_uploads_dir),
(self._settings.results_dir.resolve(), self._settings.applio_results_dir),
(self._settings.models_dir.resolve(), self._settings.applio_models_dir),
(self._settings.datasets_dir.resolve(), self._settings.applio_datasets_dir),
)
for ui_prefix, applio_prefix in mappings:
try:
relative = source.relative_to(ui_prefix)
except ValueError:
continue
return str(Path(applio_prefix) / relative)
raise _ApplioError(f"Pfad liegt außerhalb der freigegebenen Verzeichnisse: {source}")
def _verify_outputs(self, job: Job, expected: list[str]) -> None:
"""Verify that expected output files exist and are non-empty."""
missing = []
for path in expected:
p = Path(path)
if not p.exists():
missing.append(path)
elif p.is_file() and p.stat().st_size == 0:
missing.append(f"{path} (leere Datei)")
if missing:
raise _ApplioError(
"Erwartete Ergebnisdateien fehlen oder sind leer: " + ", ".join(missing)
)
def _run_convert(self, job: Job, cancel_event: threading.Event) -> None:
params = job.parameters
job.set_phase(JobPhase.VALIDATING_INPUT, "Datei wird geprüft")
input_path = params.get("input_path", "")
if not input_path or not Path(input_path).exists():
job.mark_failed(f"Eingabedatei nicht gefunden: {input_path}")
return
job.set_phase(JobPhase.PREPARING_AUDIO, "Audio wird vorbereitet")
job.set_phase(JobPhase.PREPARING_MODEL, "Modell wird geladen")
# Map paths to container
container_input = self._map_host_to_container(input_path)
container_output = self._map_host_to_container(params.get("output_path", ""))
container_pth = self._map_host_to_container(params.get("pth_path", ""))
container_index = self._map_host_to_container(params.get("index_path", ""))
job.set_phase(JobPhase.CONVERTING_VOICE, "Stimme wird umgewandelt")
args = [
"--input_path", container_input,
"--output_path", container_output,
"--pth_path", container_pth,
"--index_path", container_index,
"--pitch", str(params.get("pitch", 0)),
"--index_rate", str(params.get("index_rate", 0.3)),
"--volume_envelope", str(params.get("volume_envelope", 1.0)),
"--protect", str(params.get("protect", 0.33)),
"--f0_method", params.get("f0_method", "rmvpe"),
"--export_format", params.get("export_format", "WAV"),
]
if params.get("f0_autotune"):
args.extend(["--f0_autotune", "True", "--f0_autotune_strength", str(params.get("f0_autotune_strength", 1.0))])
if params.get("split_audio"):
args.extend(["--split_audio", "True"])
if params.get("clean_audio"):
args.extend(["--clean_audio", "True", "--clean_strength", str(params.get("clean_strength", 0.7))])
cmd = self._build_cmd("infer", args)
self._run_cmd(cmd, job, cancel_event, timeout=1800)
job.set_phase(JobPhase.SAVING_RESULT, "Ergebnis wird gespeichert")
# Verify output exists
output_file = Path(params.get("output_path", ""))
if output_file.suffix == ".wav":
export_fmt = params.get("export_format", "WAV").lower()
output_file = output_file.with_suffix(f".{export_fmt}")
self._verify_outputs(job, [str(output_file)])
job.output_files.append(str(output_file))
job.set_phase(JobPhase.COMPLETED, "Auftrag erfolgreich abgeschlossen")
job.mark_success()
def _run_tts_convert(self, job: Job, cancel_event: threading.Event) -> None:
params = job.parameters
job.set_phase(JobPhase.VALIDATING_INPUT, "Text wird geprüft")
text = params.get("text", "")
if not text:
job.mark_failed("Kein Text angegeben")
return
job.set_phase(JobPhase.SYNTHESIZING_TEXT, "Text wird in Sprache umgewandelt")
container_output_tts = self._map_host_to_container(params.get("output_tts_path", ""))
container_output_rvc = self._map_host_to_container(params.get("output_rvc_path", ""))
container_pth = self._map_host_to_container(params.get("pth_path", ""))
container_index = self._map_host_to_container(params.get("index_path", ""))
# Applio's combined ``core.py tts`` command proceeds to RVC even when
# Edge-TTS has produced an empty file. Run its bundled TTS helper as a
# separate, verified stage so a transient empty response can be retried.
tts_script = str(Path(self._settings.applio_workdir) / "rvc/lib/tools/tts.py")
unused_text_file = f"/tmp/mikes_tts_inline_{job.id}.txt"
tts_cmd = [
"docker", "exec", "-w", self._settings.applio_workdir,
self._settings.applio_container,
str(self._settings.applio_python), tts_script,
unused_text_file, text,
params.get("tts_voice", "de-DE-KatjaNeural"),
str(params.get("tts_rate", 0)), container_output_tts,
]
last_error: _ApplioError | None = None
for attempt in range(1, 3):
Path(params.get("output_tts_path", "")).unlink(missing_ok=True)
try:
self._run_cmd(tts_cmd, job, cancel_event, timeout=120)
self._verify_outputs(job, [params.get("output_tts_path", "")])
last_error = None
break
except _ApplioError as exc:
last_error = exc
if attempt == 1:
job.add_log("TTS lieferte kein gültiges Audio; zweiter Versuch")
if last_error is not None:
raise last_error
job.set_phase(JobPhase.CONVERTING_VOICE, "TTS-Stimme wird in das RVC-Modell umgewandelt")
infer_args = [
"--input_path", container_output_tts,
"--output_path", container_output_rvc,
"--pth_path", container_pth,
"--index_path", container_index,
"--pitch", str(params.get("pitch", 0)),
"--index_rate", str(params.get("index_rate", 0.3)),
"--volume_envelope", str(params.get("volume_envelope", 1.0)),
"--protect", str(params.get("protect", 0.33)),
"--f0_method", params.get("f0_method", "rmvpe"),
"--export_format", params.get("export_format", "WAV"),
]
self._run_cmd(self._build_cmd("infer", infer_args), job, cancel_event, timeout=3600)
job.set_phase(JobPhase.SAVING_RESULT, "Ergebnis wird gespeichert")
rvc_output = Path(params.get("output_rvc_path", ""))
export_fmt = params.get("export_format", "WAV").lower()
if rvc_output.suffix.lower() != f".{export_fmt}":
candidate = rvc_output.with_suffix(f".{export_fmt}")
if candidate.exists():
rvc_output = candidate
self._verify_outputs(job, [
params.get("output_tts_path", ""),
str(rvc_output),
])
# The converted voice is the user's primary result. Keep the raw TTS
# source as the optional second download for comparison.
job.output_files.extend([
str(rvc_output),
params.get("output_tts_path", ""),
])
job.set_phase(JobPhase.COMPLETED, "Auftrag erfolgreich abgeschlossen")
job.mark_success()
def _run_preprocess(self, job: Job, cancel_event: threading.Event) -> None:
params = job.parameters
job.set_phase(JobPhase.VALIDATING_INPUT, "Datensatz wird geprüft")
model_name = params.get("model_name", "")
dataset_path = params.get("dataset_path", "")
if not model_name or not dataset_path:
job.mark_failed("Modellname oder Datensatzpfad fehlt")
return
job.set_phase(JobPhase.PREPARING_AUDIO, "Audio wird vorverarbeitet")
container_dataset = self._map_host_to_container(dataset_path)
args = [
"--model-name", model_name,
"--dataset-path", container_dataset,
"--sample-rate", str(params.get("sample_rate", 40000)),
"--cut-preprocess", params.get("cut_preprocess", "Automatic"),
"--chunk-len", str(params.get("chunk_len", 3.0)),
"--overlap-len", str(params.get("overlap_len", 0.3)),
"--normalization-mode", params.get("normalization_mode", "none"),
]
if params.get("noise_reduction"):
args.append("--noise-reduction")
args.extend(["--noise-reduction-strength", str(params.get("noise_reduction_strength", 0.7))])
if params.get("process_effects"):
args.append("--process-effects")
if params.get("cpu_cores"):
args.extend(["--cpu-cores", str(params["cpu_cores"])])
cmd = self._build_cmd("preprocess", args)
self._run_cmd(cmd, job, cancel_event, timeout=3600)
model_dir = self._settings.models_dir / model_name
# Applio creates config.json only during feature extraction. A valid
# preprocessing run consists of its metadata plus matching full-rate
# and 16-kHz audio slices.
self._verify_outputs(job, [str(model_dir / "model_info.json")])
full_rate = list((model_dir / "sliced_audios").glob("*.wav"))
low_rate = list((model_dir / "sliced_audios_16k").glob("*.wav"))
if not full_rate or not low_rate:
raise _ApplioError(
"Vorverarbeitung meldete Erfolg, hat aber nicht alle Audiosegmente erzeugt"
)
if len(full_rate) != len(low_rate):
raise _ApplioError(
"Vorverarbeitung ist unvollständig: Die Zahl der Audiosegmente stimmt nicht überein"
)
job.set_phase(JobPhase.SAVING_RESULT, "Ergebnisse werden gespeichert")
job.set_phase(JobPhase.COMPLETED, "Auftrag erfolgreich abgeschlossen")
job.mark_success()
def _run_extract(self, job: Job, cancel_event: threading.Event) -> None:
params = job.parameters
job.set_phase(JobPhase.VALIDATING_INPUT, "Datensatz wird geprüft")
model_name = params.get("model_name", "")
if not model_name:
job.mark_failed("Modellname fehlt")
return
job.set_phase(JobPhase.EXTRACTING_FEATURES, "Merkmale werden extrahiert")
args = [
"--model-name", model_name,
"--f0-method", params.get("f0_method", "rmvpe"),
"--sample-rate", str(params.get("sample_rate", 40000)),
"--embedder-model", params.get("embedder_model", "contentvec"),
"--include-mutes", str(params.get("include_mutes", 0)),
]
if params.get("gpu"):
args.extend(["--gpu", str(params["gpu"])])
if params.get("cpu_cores"):
args.extend(["--cpu-cores", str(params["cpu_cores"])])
cmd = self._build_cmd("extract", args)
self._run_cmd(cmd, job, cancel_event, timeout=3600)
model_dir = self._settings.models_dir / model_name
self._verify_outputs(job, [str(model_dir / "config.json"), str(model_dir / "filelist.txt")])
expected_segments = len(list((model_dir / "sliced_audios_16k").glob("*.wav")))
extracted_features = list((model_dir / "extracted").glob("*.npy"))
f0_features = list((model_dir / "f0").glob("*.npy"))
voiced_f0_features = list((model_dir / "f0_voiced").glob("*.npy"))
if not expected_segments:
raise _ApplioError("Keine vorbereiteten Audiosegmente für die Merkmalsextraktion gefunden")
feature_counts = {
"Audiosegmente": expected_segments,
"Stimmmerkmale": len(extracted_features),
"Tonhöhe": len(f0_features),
"Stimmhafte Tonhöhe": len(voiced_f0_features),
}
if any(count != expected_segments for count in feature_counts.values()):
details = ", ".join(f"{name}: {count}" for name, count in feature_counts.items())
raise _ApplioError(f"Merkmalsextraktion ist unvollständig ({details})")
job.set_phase(JobPhase.SAVING_RESULT, "Ergebnisse werden gespeichert")
job.set_phase(JobPhase.COMPLETED, "Auftrag erfolgreich abgeschlossen")
job.mark_success()
def _run_train(self, job: Job, cancel_event: threading.Event) -> None:
params = job.parameters
job.set_phase(JobPhase.VALIDATING_INPUT, "Konfiguration wird geprüft")
model_name = params.get("model_name", "")
if not model_name:
job.mark_failed("Modellname fehlt")
return
job.set_phase(JobPhase.PREPARING_MODEL, "Trainingsumgebung wird vorbereitet")
models_dir = self._settings.models_dir / model_name
self._verify_outputs(job, [str(models_dir / "config.json"), str(models_dir / "filelist.txt")])
before = {
str(path): path.stat().st_mtime_ns
for path in models_dir.glob(f"{model_name}_*.pth")
if path.is_file()
}
job.set_phase(JobPhase.CONVERTING_VOICE, "Training läuft")
args = [
"--model-name", model_name,
"--vocoder", params.get("vocoder", "HiFi-GAN"),
"--save-every-epoch", str(params.get("save_every_epoch", 10)),
"--total-epoch", str(params.get("total_epoch", 100)),
"--sample-rate", str(params.get("sample_rate", 40000)),
"--batch-size", str(params.get("batch_size", 8)),
"--gpu", str(params.get("gpu", "0")),
"--index-algorithm", params.get("index_algorithm", "Auto"),
]
if params.get("pretrained", True):
args.append("--pretrained")
else:
args.append("--no-pretrained")
if params.get("save_only_latest"):
args.append("--save-only-latest")
if params.get("cache_data_in_gpu"):
args.append("--cache-data-in-gpu")
if params.get("checkpointing"):
args.append("--checkpointing")
if params.get("cleanup"):
args.append("--cleanup")
cmd = self._build_cmd("train", args)
self._run_cmd(cmd, job, cancel_event, timeout=7200)
job.set_phase(JobPhase.GENERATING_INDEX, "Index wird erzeugt")
job.set_phase(JobPhase.SAVING_RESULT, "Ergebnisse werden gespeichert")
pth_files = sorted(models_dir.glob(f"{model_name}_*.pth"), key=lambda p: p.stat().st_mtime_ns)
changed = [p for p in pth_files if before.get(str(p)) != p.stat().st_mtime_ns]
if not changed:
raise _ApplioError("Applio meldete Erfolg, hat aber keinen neuen oder aktualisierten Inferenz-Checkpoint erzeugt")
job.output_files.extend([str(p) for p in changed])
index_files = sorted(models_dir.glob("*.index"), key=lambda p: p.stat().st_mtime_ns)
job.output_files.extend(str(p) for p in index_files)
job.set_phase(JobPhase.COMPLETED, "Training erfolgreich abgeschlossen")
job.mark_success()
def _run_index(self, job: Job, cancel_event: threading.Event) -> None:
params = job.parameters
job.set_phase(JobPhase.VALIDATING_INPUT, "Modell wird geprüft")
model_name = params.get("model_name", "")
if not model_name:
job.mark_failed("Modellname fehlt")
return
job.set_phase(JobPhase.GENERATING_INDEX, "Index wird erzeugt")
model_dir = self._settings.models_dir / model_name
before = {str(p): p.stat().st_mtime_ns for p in model_dir.glob("*.index")}
args = [
"--model-name", model_name,
"--index-algorithm", params.get("index_algorithm", "Auto"),
]
cmd = self._build_cmd("index", args)
self._run_cmd(cmd, job, cancel_event, timeout=1800)
indexes = sorted(model_dir.glob("*.index"), key=lambda p: p.stat().st_mtime_ns)
changed = [p for p in indexes if before.get(str(p)) != p.stat().st_mtime_ns]
if not changed:
raise _ApplioError("Applio meldete Erfolg, hat aber keine neue Indexdatei erzeugt")
job.set_phase(JobPhase.SAVING_RESULT, "Index wird gespeichert")
job.output_files.extend(str(p) for p in changed)
job.set_phase(JobPhase.COMPLETED, "Auftrag erfolgreich abgeschlossen")
job.mark_success()
class _CancelledError(Exception):
pass
class _ApplioError(Exception):
pass
_real_runner: RealApplioRunner | None = None
def get_real_runner() -> RealApplioRunner:
global _real_runner
if _real_runner is None:
_real_runner = RealApplioRunner()
return _real_runner