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.
449 lines
15 KiB
Python
449 lines
15 KiB
Python
"""Job management endpoints."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import shutil
|
|
from pathlib import Path
|
|
from typing import Any, Literal
|
|
|
|
from fastapi import APIRouter, HTTPException, Request
|
|
from fastapi.responses import FileResponse
|
|
from pydantic import BaseModel, Field, field_validator
|
|
|
|
from ..config import get_settings
|
|
from ..jobs.enums import JobStatus, JobType
|
|
from ..jobs.models import Job, JobResponse
|
|
from ..jobs.queue import JobQueue
|
|
from ..services.models import validate_model_name
|
|
|
|
router = APIRouter(tags=["jobs"])
|
|
|
|
|
|
def _get_queue(request: Request) -> JobQueue:
|
|
return request.app.state.job_queue
|
|
|
|
|
|
def _get_store(request: Request):
|
|
return request.app.state.job_store
|
|
|
|
|
|
def _require_realtime_idle(request: Request) -> None:
|
|
if getattr(request.app.state, "realtime_active", False):
|
|
raise HTTPException(
|
|
status_code=409,
|
|
detail="Während einer Live-Umwandlung können keine anderen Applio-Aufträge gestartet werden",
|
|
)
|
|
|
|
|
|
def _safe_upload_path(value: str) -> Path:
|
|
"""Resolve an uploaded file without allowing arbitrary host paths."""
|
|
settings = get_settings()
|
|
uploads_root = settings.uploads_dir.resolve()
|
|
candidate = Path(value)
|
|
if not candidate.is_absolute():
|
|
matches = list(uploads_root.glob(f"{value}/{value}_*"))
|
|
if len(matches) != 1:
|
|
raise HTTPException(status_code=400, detail="Upload konnte nicht eindeutig gefunden werden")
|
|
candidate = matches[0]
|
|
candidate = candidate.resolve()
|
|
try:
|
|
candidate.relative_to(uploads_root)
|
|
except ValueError as exc:
|
|
raise HTTPException(status_code=400, detail="Ungültiger Upload-Pfad") from exc
|
|
if not candidate.is_file():
|
|
raise HTTPException(status_code=404, detail="Upload-Datei nicht gefunden")
|
|
return candidate
|
|
|
|
|
|
def _result_dir(job_id: str) -> Path:
|
|
path = get_settings().results_dir / job_id
|
|
path.mkdir(parents=True, exist_ok=True)
|
|
return path
|
|
|
|
|
|
# --- Request models ---
|
|
|
|
class NamedModelRequest(BaseModel):
|
|
model_name: str
|
|
|
|
@field_validator("model_name")
|
|
@classmethod
|
|
def safe_model_name(cls, value: str) -> str:
|
|
return validate_model_name(value)
|
|
|
|
|
|
class ConvertRequest(NamedModelRequest):
|
|
input_path: str
|
|
preset_id: str | None = None
|
|
pitch: int = Field(default=0, ge=-24, le=24)
|
|
f0_method: Literal["rmvpe", "crepe", "crepe-tiny", "fcpe"] = "rmvpe"
|
|
index_rate: float = Field(default=0.3, ge=0, le=1)
|
|
protect: float = Field(default=0.33, ge=0, le=0.5)
|
|
volume_envelope: float = Field(default=1.0, ge=0, le=1)
|
|
export_format: Literal["WAV", "MP3", "FLAC"] = "WAV"
|
|
f0_autotune: bool = False
|
|
f0_autotune_strength: float = Field(default=1.0, ge=0, le=1)
|
|
split_audio: bool = False
|
|
clean_audio: bool = False
|
|
clean_strength: float = Field(default=0.7, ge=0, le=1)
|
|
|
|
|
|
class TTSConvertRequest(NamedModelRequest):
|
|
text: str
|
|
tts_voice: str = "de-DE-KatjaNeural"
|
|
tts_rate: int = Field(default=0, ge=-100, le=100)
|
|
preset_id: str | None = None
|
|
pitch: int = Field(default=0, ge=-24, le=24)
|
|
f0_method: Literal["rmvpe", "crepe", "crepe-tiny", "fcpe"] = "rmvpe"
|
|
index_rate: float = Field(default=0.3, ge=0, le=1)
|
|
protect: float = Field(default=0.33, ge=0, le=0.5)
|
|
export_format: Literal["WAV", "MP3", "FLAC"] = "WAV"
|
|
|
|
|
|
class PreprocessRequest(NamedModelRequest):
|
|
dataset_path: str
|
|
sample_rate: Literal[32000, 40000, 48000] = 40000
|
|
cut_preprocess: str = "Automatic"
|
|
noise_reduction: bool = False
|
|
noise_reduction_strength: float = Field(default=0.7, ge=0, le=1)
|
|
process_effects: bool = False
|
|
chunk_len: float = Field(default=3.0, ge=0.5, le=5.0)
|
|
overlap_len: float = Field(default=0.3, ge=0.0, le=0.4)
|
|
normalization_mode: str = "none"
|
|
cpu_cores: int | None = Field(default=None, ge=1, le=64)
|
|
|
|
|
|
class ExtractRequest(NamedModelRequest):
|
|
f0_method: Literal["rmvpe", "crepe", "crepe-tiny", "fcpe"] = "rmvpe"
|
|
sample_rate: Literal[32000, 40000, 48000] = 40000
|
|
embedder_model: str = "contentvec"
|
|
include_mutes: int = Field(default=0, ge=0, le=10)
|
|
gpu: str | None = None
|
|
cpu_cores: int | None = Field(default=None, ge=1, le=64)
|
|
|
|
|
|
class TrainRequest(NamedModelRequest):
|
|
vocoder: str = "HiFi-GAN"
|
|
total_epoch: int = Field(default=100, ge=1, le=10000)
|
|
save_every_epoch: int = Field(default=10, ge=1, le=100)
|
|
save_only_latest: bool = False
|
|
sample_rate: Literal[32000, 40000, 48000] = 40000
|
|
batch_size: int = Field(default=8, ge=1, le=50)
|
|
gpu: str = "0"
|
|
pretrained: bool = True
|
|
cache_data_in_gpu: bool = False
|
|
checkpointing: bool = False
|
|
cleanup: bool = False
|
|
index_algorithm: str = "Auto"
|
|
|
|
|
|
class IndexRequest(NamedModelRequest):
|
|
index_algorithm: str = "Auto"
|
|
|
|
|
|
# --- Endpoints ---
|
|
|
|
@router.get("/jobs")
|
|
def list_jobs(
|
|
request: Request,
|
|
status: JobStatus | None = None,
|
|
limit: int = 100,
|
|
offset: int = 0,
|
|
):
|
|
store = _get_store(request)
|
|
jobs = store.list(status=status, limit=limit, offset=offset)
|
|
total = store.count(status=status)
|
|
return {
|
|
"jobs": [JobResponse.from_job(j) for j in jobs],
|
|
"count": len(jobs),
|
|
"total": total,
|
|
}
|
|
|
|
|
|
@router.get("/jobs/summary")
|
|
def job_summary(request: Request):
|
|
queue = _get_queue(request)
|
|
store = _get_store(request)
|
|
running = queue.get_running()
|
|
waiting = store.list(status=JobStatus.WAITING, limit=50)
|
|
recent = store.list(limit=10)
|
|
return {
|
|
"running": [JobResponse.from_job(j) for j in running],
|
|
"waiting": [JobResponse.from_job(j) for j in waiting],
|
|
"recent": [JobResponse.from_job(j) for j in recent],
|
|
"counts": {
|
|
"running": len(running),
|
|
"waiting": len(waiting),
|
|
"total": store.count(),
|
|
},
|
|
}
|
|
|
|
|
|
def _remove_job_results(job_id: str) -> None:
|
|
"""Remove only this job's private result directory, never model artifacts."""
|
|
results_root = get_settings().results_dir.resolve()
|
|
target = (results_root / job_id).resolve()
|
|
if target.parent == results_root and target.is_dir():
|
|
shutil.rmtree(target)
|
|
|
|
|
|
@router.delete("/jobs")
|
|
def clear_finished_jobs(request: Request):
|
|
"""Clear the visible history of all terminal jobs and their result files."""
|
|
store = _get_store(request)
|
|
deleted_ids = store.delete_all_terminal()
|
|
for job_id in deleted_ids:
|
|
_remove_job_results(job_id)
|
|
return {"status": "ok", "deleted": len(deleted_ids)}
|
|
|
|
|
|
@router.get("/jobs/{job_id}")
|
|
def get_job(request: Request, job_id: str):
|
|
queue = _get_queue(request)
|
|
live_job = next((job for job in queue.get_running() if job.id == job_id), None)
|
|
if live_job is not None:
|
|
return JobResponse.from_job(live_job)
|
|
store = _get_store(request)
|
|
job = store.get(job_id)
|
|
if job is None:
|
|
raise HTTPException(status_code=404, detail=f"Job '{job_id}' nicht gefunden")
|
|
return JobResponse.from_job(job)
|
|
|
|
|
|
@router.delete("/jobs/{job_id}")
|
|
def delete_finished_job(request: Request, job_id: str):
|
|
"""Delete one terminal job and its private result directory."""
|
|
store = _get_store(request)
|
|
job = store.get(job_id)
|
|
if job is None:
|
|
raise HTTPException(status_code=404, detail=f"Job '{job_id}' nicht gefunden")
|
|
if not job.is_terminal():
|
|
raise HTTPException(
|
|
status_code=409,
|
|
detail="Laufende oder wartende Aufträge können nicht gelöscht werden",
|
|
)
|
|
if not store.delete_terminal(job_id):
|
|
raise HTTPException(status_code=409, detail="Auftrag konnte nicht gelöscht werden")
|
|
_remove_job_results(job_id)
|
|
return {"status": "ok", "job_id": job_id}
|
|
|
|
|
|
@router.get("/jobs/{job_id}/log")
|
|
def get_job_log(request: Request, job_id: str):
|
|
queue = _get_queue(request)
|
|
live_job = next((job for job in queue.get_running() if job.id == job_id), None)
|
|
if live_job is not None:
|
|
return {"job_id": job_id, "log": live_job.log, "count": len(live_job.log)}
|
|
store = _get_store(request)
|
|
job = store.get(job_id)
|
|
if job is None:
|
|
raise HTTPException(status_code=404, detail=f"Job '{job_id}' nicht gefunden")
|
|
return {"job_id": job_id, "log": job.log, "count": len(job.log)}
|
|
|
|
|
|
@router.post("/jobs/{job_id}/cancel")
|
|
def cancel_job(request: Request, job_id: str):
|
|
queue = _get_queue(request)
|
|
if not queue.cancel(job_id):
|
|
raise HTTPException(status_code=400, detail="Job kann nicht abgebrochen werden (bereits beendet oder nicht gefunden)")
|
|
return {"status": "ok", "job_id": job_id}
|
|
|
|
|
|
@router.post("/jobs/{job_id}/retry")
|
|
def retry_job(request: Request, job_id: str):
|
|
queue = _get_queue(request)
|
|
store = _get_store(request)
|
|
job = store.get(job_id)
|
|
if job is None:
|
|
raise HTTPException(status_code=404, detail=f"Job '{job_id}' nicht gefunden")
|
|
if not job.is_terminal():
|
|
raise HTTPException(status_code=400, detail="Nur abgeschlossene Jobs können wiederholt werden")
|
|
|
|
new_job = Job(
|
|
type=job.type,
|
|
parameters=dict(job.parameters),
|
|
input_files=list(job.input_files),
|
|
model_name=job.model_name,
|
|
)
|
|
if new_job.type == JobType.CONVERT:
|
|
result_dir = _result_dir(new_job.id)
|
|
new_job.parameters["output_path"] = str(result_dir / "converted.wav")
|
|
elif new_job.type == JobType.TTS_CONVERT:
|
|
result_dir = _result_dir(new_job.id)
|
|
# Applio's bundled Edge-TTS backend writes MPEG audio. The temporary
|
|
# filename must reflect that format or the RVC loader treats it as a
|
|
# corrupt WAV file.
|
|
new_job.parameters["output_tts_path"] = str(result_dir / "tts.mp3")
|
|
new_job.parameters["output_rvc_path"] = str(result_dir / "converted.wav")
|
|
queue.submit(new_job)
|
|
return {"status": "ok", "new_job_id": new_job.id}
|
|
|
|
|
|
@router.get("/jobs/{job_id}/download")
|
|
def download_job_output(request: Request, job_id: str, file_index: int = 0):
|
|
store = _get_store(request)
|
|
job = store.get(job_id)
|
|
if job is None:
|
|
raise HTTPException(status_code=404, detail=f"Job '{job_id}' nicht gefunden")
|
|
if not job.output_files:
|
|
raise HTTPException(status_code=404, detail="Keine Ergebnisdateien vorhanden")
|
|
if file_index < 0 or file_index >= len(job.output_files):
|
|
raise HTTPException(status_code=404, detail="Datei-Index außerhalb des Bereichs")
|
|
|
|
path = job.output_files[file_index]
|
|
p = Path(path)
|
|
if not p.exists():
|
|
raise HTTPException(status_code=404, detail=f"Datei nicht gefunden: {p.name}")
|
|
|
|
return FileResponse(
|
|
path=str(p),
|
|
filename=p.name,
|
|
media_type=_guess_media_type(p.suffix),
|
|
)
|
|
|
|
|
|
def _guess_media_type(suffix: str) -> str:
|
|
types = {
|
|
".wav": "audio/wav",
|
|
".mp3": "audio/mpeg",
|
|
".flac": "audio/flac",
|
|
".ogg": "audio/ogg",
|
|
".m4a": "audio/mp4",
|
|
".aac": "audio/aac",
|
|
".pth": "application/octet-stream",
|
|
".index": "application/octet-stream",
|
|
}
|
|
return types.get(suffix.lower(), "application/octet-stream")
|
|
|
|
|
|
# --- Job creation endpoints ---
|
|
|
|
@router.post("/jobs/convert")
|
|
def create_convert_job(request: Request, body: ConvertRequest):
|
|
_require_realtime_idle(request)
|
|
queue = _get_queue(request)
|
|
|
|
from ..services.models import get_model
|
|
model = get_model(body.model_name)
|
|
if model is None:
|
|
raise HTTPException(status_code=404, detail=f"Modell '{body.model_name}' nicht gefunden")
|
|
elif not model.pth_path:
|
|
raise HTTPException(status_code=400, detail=f"Modell '{body.model_name}' hat keine PTH-Datei")
|
|
elif not model.index_path:
|
|
raise HTTPException(status_code=400, detail=f"Modell '{body.model_name}' hat keine Index-Datei")
|
|
|
|
params = _merge_preset(body)
|
|
|
|
input_path = _safe_upload_path(body.input_path)
|
|
job = Job(
|
|
type=JobType.CONVERT,
|
|
model_name=body.model_name,
|
|
parameters=params,
|
|
input_files=[str(input_path)],
|
|
)
|
|
output_path = _result_dir(job.id) / "converted.wav"
|
|
job.parameters.update({
|
|
"input_path": str(input_path),
|
|
"output_path": str(output_path),
|
|
"pth_path": model.pth_path,
|
|
"index_path": model.index_path,
|
|
})
|
|
queue.submit(job)
|
|
return {"status": "ok", "job_id": job.id}
|
|
|
|
|
|
@router.post("/jobs/tts-convert")
|
|
def create_tts_convert_job(request: Request, body: TTSConvertRequest):
|
|
_require_realtime_idle(request)
|
|
queue = _get_queue(request)
|
|
|
|
from ..services.models import get_model
|
|
model = get_model(body.model_name)
|
|
if model is None:
|
|
raise HTTPException(status_code=404, detail=f"Modell '{body.model_name}' nicht gefunden")
|
|
elif not model.pth_path or not model.index_path:
|
|
raise HTTPException(status_code=400, detail=f"Modell '{body.model_name}' ist nicht einsatzbereit")
|
|
|
|
params = _merge_preset(body)
|
|
|
|
job = Job(
|
|
type=JobType.TTS_CONVERT,
|
|
model_name=body.model_name,
|
|
parameters=params,
|
|
)
|
|
result_dir = _result_dir(job.id)
|
|
job.parameters.update({
|
|
"output_tts_path": str(result_dir / "tts.mp3"),
|
|
"output_rvc_path": str(result_dir / "converted.wav"),
|
|
"pth_path": model.pth_path,
|
|
"index_path": model.index_path,
|
|
})
|
|
queue.submit(job)
|
|
return {"status": "ok", "job_id": job.id}
|
|
|
|
|
|
@router.post("/jobs/preprocess")
|
|
def create_preprocess_job(request: Request, body: PreprocessRequest):
|
|
_require_realtime_idle(request)
|
|
queue = _get_queue(request)
|
|
job = Job(
|
|
type=JobType.PREPROCESS,
|
|
model_name=body.model_name,
|
|
parameters=body.model_dump(),
|
|
)
|
|
queue.submit(job)
|
|
return {"status": "ok", "job_id": job.id}
|
|
|
|
|
|
@router.post("/jobs/extract")
|
|
def create_extract_job(request: Request, body: ExtractRequest):
|
|
_require_realtime_idle(request)
|
|
queue = _get_queue(request)
|
|
job = Job(
|
|
type=JobType.EXTRACT,
|
|
model_name=body.model_name,
|
|
parameters=body.model_dump(),
|
|
)
|
|
queue.submit(job)
|
|
return {"status": "ok", "job_id": job.id}
|
|
|
|
|
|
@router.post("/jobs/train")
|
|
def create_train_job(request: Request, body: TrainRequest):
|
|
_require_realtime_idle(request)
|
|
queue = _get_queue(request)
|
|
job = Job(
|
|
type=JobType.TRAIN,
|
|
model_name=body.model_name,
|
|
parameters=body.model_dump(),
|
|
)
|
|
queue.submit(job)
|
|
return {"status": "ok", "job_id": job.id}
|
|
|
|
|
|
@router.post("/jobs/index")
|
|
def create_index_job(request: Request, body: IndexRequest):
|
|
_require_realtime_idle(request)
|
|
queue = _get_queue(request)
|
|
job = Job(
|
|
type=JobType.INDEX,
|
|
model_name=body.model_name,
|
|
parameters=body.model_dump(),
|
|
)
|
|
queue.submit(job)
|
|
return {"status": "ok", "job_id": job.id}
|
|
|
|
|
|
def _merge_preset(body: ConvertRequest | TTSConvertRequest) -> dict[str, Any]:
|
|
"""Apply a preset first, then overlay fields explicitly supplied by the client."""
|
|
explicit = body.model_dump(include=body.model_fields_set)
|
|
params: dict[str, Any] = body.model_dump()
|
|
if body.preset_id:
|
|
from ..services.presets import get_preset
|
|
preset = get_preset(body.preset_id)
|
|
if preset is None:
|
|
raise HTTPException(status_code=404, detail=f"Preset '{body.preset_id}' nicht gefunden")
|
|
params.update(preset.parameters)
|
|
params.update(explicit)
|
|
return params
|